05-couplinglr.pdf

13
Neither the structure chart, which we explored in Chapter 3, nor module specifications, which we considered in Chapter 4, in themselves tell us very much about the quality of a particular design. Structured Design is not the structure chart any more than good sculpture is a chisel. The chisel is a tool for chipping that must be used with dexterity to achieve a good result. Similarly, a structure chart is simply a tool for showing a picture of the modules in a system and their relationships to one another. One of the fundamental principles of Structured Design is that a large system should be partitioned into manageable modules. However, it is vital that this partitioning should be carried out in such a way that the modules are as independent as possible-this is the criterion of coupling, which is covered in Chapter 5-and that each module carries out a single, problem-related func- tion-this is the criterion of cohesion, which is discussed in Chapter 6. Although these two complementary measures of partitioning, and cou- pling and cohesion, are central themes in Structured Design, there are many other guidelines that can be used to evaluate and improve the quality of a design. These guidelines are explained in Chapter 7 and are summarized in Appendix A. 57

Upload: julioces01

Post on 14-Sep-2015

217 views

Category:

Documents


1 download

TRANSCRIPT

  • Neither the structure chart, which we explored in Chapter 3, nor modulespecifications, which we considered in Chapter 4, in themselves tell us verymuch about the quality of a particular design. Structured Design is not thestructure chart any more than good sculpture is a chisel. The chisel is a tool forchipping that must be used with dexterity to achieve a good result. Similarly, astructure chart is simply a tool for showing a picture of the modules in a systemand their relationships to one another.

    One of the fundamental principles of Structured Design is that a largesystem should be partitioned into manageable modules. However, it is vitalthat this partitioning should be carried out in such a way that the modules areas independent as possible-this is the criterion of coupling, which is coveredin Chapter 5-and that each module carries out a single, problem-related func-tion-this is the criterion of cohesion, which is discussed in Chapter 6.

    Although these two complementary measures of partitioning, and cou-pling and cohesion, are central themes in Structured Design, there are manyother guidelines that can be used to evaluate and improve the quality of adesign. These guidelines are explained in Chapter 7 and are summarized inAppendix A.

    57

  • Chap. 5 Coupling 59

    5

    Coupling

    In this chapter and in subsequent chapters, we use the structure chart to evalu-ate the quali ty of system des ign. One way of measuring des ign quality is cou-pl!n~, ~e degree of interdependence between two modules. Our objective is tommln,tlze coupling, that is, to make modules as ind ependent as possible. Low

    cou~lmg. between modules indicates a well-partitioned system and can beattained m one of the three following ways:

    1. by eliminating unnecessary relationships,2. by reducing the number of nec essary relationships, and3. by easing the " tightness" of necessary relationships.

    Before I define what I mean by "tightness," let's return to the analogy of~ha?ter 1, the stereo sys tem. Visualize a typ ical system. in which each speakerIS. d~rectly coupled to the amplifier; without the amplifier, it would be silent.Similarly, the amplifier is directly coupled to the turntable. The speakers,h?wev~r, are not coupled to each oth er, because we could unplug one withoutdisturbing the other.

    The coupling in th is stereo is about as low as we can get. If we remo vedany of the conn~cti?ns be~een the modules, the stereo wouldn't work prop-erly. The coupling IS also loose" in the sense that we can detach the modules

    58

    from one another by pulling out plugs. To detach the turntable from the ampli-fier, we don 't need to disassemble either the turntable or the amplifier or toburn costly printed-circuit boards [or our fingers!) with a soldering iron. Sol-dered-in leads, or cords, cons titute a tighter coupling.

    Let's take this neat and sensible organization and ruin its clean coupling.To make the point, I'll do it in a way that would be a nightmare to any stereouser. First, we will route the power supply for the amplifier through the rightspeaker. This is an extra piece of coupling between the speaker and the ampli-fier th at, of course, is totally superfluous. Although the stereo will still workperfectl y, we've created some diabo lical maintenance problems. For example,if we need to send the right speaker away to be fixed, we'll have to do withoutthe amplifier, too. If we want to buy better speakers, we 'll have to finda pair whose right speaker has a power supply [a lim ited marketl) . Thespeaker builder has his job mad e pointlessly more complicated by having tocope with a power supply [which is quite irrelevant to the operation of aspeaker).

    Second, let's not plug the left speaker into the amplifier-let's drill a holein the amplifier case and solder the speaker lead s directly. By doing this, we'vecreated more problems. For example. it' s important to know the design andwiring layout of the amp lifier since a wire soldered in the wrong place coulddestroy the speaker or the amplifier or both , Also , changing amplifiers be-comes painful. We'll have to do some tedious soldering, and we'll have tolearn the internal details of yet another amplifier.

    Third, let's abandon all modularity and put everytiIing- speakers andall- in to one big box. By doing this, we cause the foHowing to happen. Wecan't fit the box on one shelf; the speakers are too close to each oilier for the sizeof the room; and, unexpectedly, th e in ductive field from the turntable motorcauses a deep hum in th e amplifier. The speakers sound terrible in the boxbecause the sound waves interfere with one another, destroying response atsome frequencies. Th ere is very littl e that we can do about these spuriouseffects of one part of the system on ano ther part short of chopping the systeminto modules once again .

    Each of these three systems has wors e coupling [and, consequently, worsepartitioning) than th e original clean system. The original system is coupled, ofcourse, which means that connected modules must agree on some details. Forexample, the speakers an d the amplifier must correspond in impedance. Also,the turntable has to have a plug tha t fits the amplifier's input socket.

    However. one of the crucial points of th is low coupling is that no modulehas to worry about the particular intern al construction details of any oilier.Modules are seen by their function and external app earance-iliat is, as blackboxes .

    To sum up, low coupling is desirable becaus e

    the fewer connections there are between two modules. the less chancethere is for the ripple efiect [a defect in one module app earing as a symp-tom in another) :

  • 60 Coupling Chap.S Sec. 5.1 The Principles of Coupling 61

    we want to be able to change one module with minimum risk of having tochange another module, and we want each user change to affect as fewmodules as possible; and

    while maintaining a module, we don't want to worry about the internal(coding) details of any other module; we want the system to be as simpleto understand as possible.

    5.1 THE PRINCIPLES OF COUPUNG

    Reducing the coupling between modules means, in effect, reducing the com-plexity of the connection(s) between the modules as much as possible. Toparaphrase Einstein, we seek to make such connections as simple as the appli-cation will allow, and no simpler. The principles by which to reduce couplingare the following, which I have adapted from Chapter 5 of Yourdon and Con-stantine (1978).

    1. Create narrow (as opposed to hroad) connections.2. Create direct (as opposed to indirect) connections.3. Create local (as opposed to remote) connections.4. Create obvious (as opposed to obscure) connections.5. Create flexible (as opposed to rigid) connections.

    The next five sections will elaborate on these five principles.

    5.1.1 Narrow Ivs. Broad) Connections

    The breadth of an interface between two modules is essentially the number ofconnections that link the two modules. By analogy with the stereo system, it isthe "number of wires" that connects the two components of the system. Anexample of narrow (that is, good) coupling would be a pair of modules thatcommunicated only two pieces of data from one to the other. An example ofbroad (that is, worse) coupling would be another pair of modules that commu-nicated 15 pieces of data back and forth.

    5.1.2 Direct Ivs. Indirect) Connections

    The interface between two modules is more understandable-and thus lesscomplex in human terms-if a person can comprehend it directly, withouthaving to refer to several other pieces of information first. For example, if amodule uses a piece of data called CUST-DETAILS, which is defined to beCUST-NAME, CUST-ACCOUNT-NUM, CUST-ADDRESS and CUST-BAL-ANCE, then a person trying to understand the module's connection to the

    outside world would have to look up the definition of CUST-DETAILS first. Hemay then have to look up the definition of CUST-ADDRESS, too.

    Note that when I talk about direct vs. indirect connections and otherprinciples of coupling, I'm talking about the issues in human, not computer,terms. For instance, I'm not referring to indirect memory addressing, unlessthe practice of indirect addressing also forces a maintenance programmer to gothrough his own mental levels of indirection. The reason for this- human em-phasis is, of course. the huge "peopleware" cost of computer systems, which Idescribed in Section 2.2.5.

    5.1.3 Local (vs. Remote) Connections

    If all the information required to understand the connection between two mod -ules is presented with the connection itself [e.g., by means of a parameter listalongside a call to a module). then the information is s~id to be local. Anexample of remote information might be a module connection throu~ a gl~balpiece of data. In this case. the information about the module connection mightbe hundreds of lines away in the listing from either the calling or the calledmodule. Also. the connection might be remote in time, in that the value of thedata may have been set long before it is actually used. This additional remote-ness further adds to the expense of understanding the interface.

    5.1.4 Obvious (ys. Obscure) Connections

    It is almost tautological to say than an obvious connection between modules iseasier to understand than an obscure one. Nevertheless, it is worth stating, forin my experience a great deal of expense has been gratuitously introduced intosystems by designers who have delighted in indulging in arcane mechanisms toconnect their modules.

    I will present several examples of obscure connections in later sections.But I will offer two small examples here. An assembler-language routine (sayA) that communicates with a routine B by modifying the contents of a table in Bis indulging in obscure coupling. In order for a person maintaining routine B tounderstand how that data got into the table, he may have to carry out a greatdeal of detective work.

    The second example of obscurity'comes from a system that I once encoun-tered in a bank. In this-system, telephone numbers were represented with thearea code last. (For instance, my business number, which is 206 839 4042,would become 8394042206.) Even though this peculiar representation waswell documented, it was evident that not everyone had read the documenta-tion. since half of one new system's reports showed phone numbers in the form(839) 404-2206! The problem with this representation is that it's nonstandardand hence obscure. Any data structure that hails from "Tales of the Unex-

  • 62 Coupling Chap. 5 Sec. 5.2 Normal Coupling 63

    pected" tends to introduce errors into a system. usually through unwarranted(but very natural) assumptions on the part of the system's maintainers.

    5.1.5 Flexible (vs. Rigid) ConnectionsA c

    Two modules, A and B, are normally coupled if (1) A calls B, (2) B returns to A,and (3) all information passed between them is by means of parameters pre-sented with the call itself. This , of course , is the situation depicted on a normalstructure chart, as shown in Figures 5.2 and 5.3.

    In Figure 5.2, A calls B, but neither passes anything to B nor receivesanything from B. This (admittedly rare) situation marks a zero point on thescale of coupling; A is coupled to B only in that A uses B's name. (So if Bchanged its name, A would have to be changed. too.)

    The maintenance of a computer system often involves changes to the linksamong the system's modules. For instance. you may need to hook a module toa module other than those to which it is already attached. Or, you may want tochange the information being passed to or from the module. If the mechanismthat the ori~nal designer chose to connect the module to its fellows is rigid,then you will suffer great difficulty and cost in making the change.

    . An example of a rigid connection would be one in which a designer haddecided that a module should collect the information it needed from a fixedlocation in memory. In that case, if you had to reuse that module in a differentpart of the system, you would either have to goof up the previous usage of thememory location or have to write some ugly little wart of code to get around theproblem.

    Having looked at the five desirable qualities of connections among mod-ules-s-that they should be narrow, direct, local, obvious , and flexible in order toreduce the cost of system maintenance-look now at what this means in practi-cal terms to the design of systems. There are three broad classes of couplingthat systems designers have traditionally used to connect modules: normalcoupling, common coupling, and content coupling. In terms of StructuredDesign, these classes are, respectively, acceptable, unacceptable, and forbid-den. (In the following sections I will explain each class in detail, and I willjustify my judgments.)

    . Since Il;0rmal coupling is such a worthy stalwart of Structured Design. wewill look at It most closely, especially in terms of the concepts of data , stamp,and control coupling. In short, then, the types of coupling that we'll exploreare shown in Figure 5.1.

    DA and B Normal lV

    Coupled . but HavingNoth ing to Say to

    Each Other

    Figure 5.2

    5.2 NORMAL COUPLING1

    o

    C and 0 NormallyCoup led and

    CommunicatingData X and Y

    Figure S.3

    Best

    NORMALDateStampControl

    COMMON

    CONTENT

    5.2.1 Data Coupling

    Figure 5.3 represents by far the most usual type of coupling found in systems:normal coupling by means of data, or data coupling.

    Two modules are data coupled if they communicate by parameters, eachparameter being an elementary piece of data. Data coupling is the necessarycommunication of data between modules. Since modules must communicate,data coupling is unavoidable and is quite harmless as long as it 's kept to aminimum. In the exainple of Figure 5.4. all four pieces of data-SUM BOR-ROWED, INTEREST RATE, TERM, and REPAYMENT RATE-are necessary.

    1 Th is term is an adaptation of "nonnal connection." as used in Yourdon and Constantine,

    Worst Figure S.l 1978.

  • 64 Coupling Chap. 5Sec. 5.2 Normal Coupling 65

    1. I must.empha~ize. however, that with data coupling. as with all coupling.small IS beautiful. A raucous mob of parameters crossing an interface ismore likely to harbor a bug than is a small, well-disciplined bunch ofparaJ.lleters. Also. an unruly throng of, say, 20 parameters is likely toprovide a wealth of obscurity for the poor maintenance programmer.(And probably such a wide interface would cast doubt on the cohesion ofone or more modules; this is covered in Chapter 6.) So keep your inter-faces as narrow as possible. .

    On the other hand. nothing extra is needed. To send down, say, CUSTOMERNAME would add extra complication without being of use to CALCULATEMORTGAGE PAYMENT.

    Data coupling shows all the best characteristics of coupling that wereoutline~ in Section 5.1. It is narrow, at least it is if you avoid sending unnec-cessary Junk (e.g. CUSTOMERNAME in the above example) across the inter-face. It is direct; what you see is what you get. It is local; in the code, the actualcoupling is shown alongside the call in the calling module as well as the start of~e called. module. It is obvious ; no trickery or sleight of hand is at work. (Adifficulty ill most languages, however, is figuring out from the code which data"goes down the call" and which "comes up." But the structure chart and goodco~ents. or the use of a language such as Ada. will resolve that.) Finally. it isflexible, The called module can be quickly replaced by any other "plug com-patible" module. Alternatively, the called module can easily be used by an-other caller, for it need know nothing about the module calling it.

    Two Warnings About Data Coupling

    5.2.2 Stamp Coupling2

    2. Look at the piece of structure chart in Figure 5.5. At first glance. thecoupling in this system looks good. But MASTER RECORD is suspi-cious. It first enters the system at GET CUSTOMER MASTER.but it takesa roundabout route to reach UPDATE MASTER, where it is used. MAS-TER RECORD is an example of what I call a tramp, a piece of informationthat shuffles aimlessly around a system. unwanted by and meaningless tomost of the modules through which it passes . Like a hobo. such trampdata is a nuisance to many modules (for example, GET VALID INPUT).which need extra code in order to drive it out of their neighborhoodstoward a module that can make use of it. In addition. the more modules apiece of tramp data travels through. the more likely that it will be acciden-tally altered, or that it will spread a defect. To varying extents, tramp dataviolates all five of the principles for good coupling.

    Tramp data is a symptom of poor organization of modules. In the case ofFigure 5.5, GET CUSTOMER MASTER should be directly subordinate to UP-DATE CUSTOMER MASTER FILE. (I discuss poss ible causes of tramp datawhen I address cohesion and decision-splitting in Chapters 6 and 7. respec-tively.)

    Two normally coupled modules are stamp coupled if one passes to the other acomposite piece of data . that is. a piece of data with meaningful internal struc-ture. Examples of composite data might be a CUSTOMER-RECORD comprisingmany fields. Figure 5.6 shows two stamp-coupled modules.

    The three parameters in Figure 5.6. CHESS-BOARD. MOVE, and NEW-CHESS-BOARD. all presumably have rich internal structures, thus making thetwo modules shown stamp coupled. This is fine. The data structures chosenare natural to the application and there is no gratuitous obscurity. However.there is some indirectness introduced. To be really sure about what's going onhere. we need to take the time to look up the definitions of MOVEand CHESS-BOARD. This indirectness is the reason that stamp coupling is a little lower onthe scale than data coupling. However. this is a small price to pay for avoidingan unconscionably broad interface. For instance. it would be absurd to pass 64(or more) separate pieces of data to MAKEMOVE in order to represent a chessboard. .

    Although good designers use stamp coupling well . bad designers do bi-zarre things with it. So, two more warnings are in order.

    , This term wes coined by Myers (1975).

    1. Never pass records containing many fields to modules that need only oneor two of those fields. Figure 5.7 shows three stamp-coupled modules.

    Two Warnings About Stamp Coupling

    I

    Figure 5.4 Two data-coupled modules

    ent Rate

    ASSESSHOUSE

    AFFOROABILITY

    Termiest Ratei 1Repaymarrowedi

    CALCULATEMORTGAGEREPAYMENT

    Inter

    SumB

  • 66 Coupling Chap. 5 Sec. 5.2 Normal Coupling 67

    UPDATECUSTOMER

    MASTER FILE

    PLAYCHESS

    GETVALID UPDATEINPUT MASTER

    Figure 5.6 Stamp-coupled modules

    1NewChessBoardMove rChess ?Board!

    r:lL:J

    be changed, or at least recompiled, although these modules do not refer toMerlin Club members.

    The problem inherent in such unnecessary use of stamp coupling isthat it creates dependencies between otherwise unrelated modules. Inaddition, other problems exist, as shown in Figure 5.8. VALIDATEPHONE NUMBER is one of those modules that should be written onlyonce in a lifetime and then used over and over whenever you get theopportunity. But don't write one like the module in Figure 5.8! If youwanted to use this module in another system (or even elsewhere in thisone). you would have to remember to dummy up a record to look like a .CUSTOMER RENTAL RECORD from this particular system.

    PUTCUSTOMER

    MASTER

    MasterrRecord 1UpdatedMaster

    Valid i RecordTrans-action

    VALI DATECUSTOMER

    TRANSACTION

    GETCUSTOMER

    MASTER

    0..~ TransactionTransaction' IsValid

    MasterReco~

    GETINPUT

    GETCUSTOMER

    TRANS

    Figure 5.5GENERATECUSTOMER

    RENTALBILL

    CUSTOMER RENTAL RECORD comprises many fields: LICENSE NUM-BER, MERLIN CLUB MEMBERSHIP, MERLIN CLUB NUMBER, GASUSED, CAR TYPE, MILES DRIVEN, and DAYS USED, among others.Although the module CALCULATE BASIC RENTAL CHARGE requiresonly the last three fields mentioned, it receives the whole CUSTOMERRENTAL RECORD. Any change to this record, either in format or instructure, will affect all of the modules that refer to it, even those modulesthat don't refer to the actual fields changed. "

    As a simple example, let's imagine that the field MERLIN CLUBNUMBER is changed in format. Both the modules CALCULATE BASICRENTAL CHARGE and CALCULATE GASOLINE CHARGE will have to

    CustomerRental 1/, BasicRecord Rental

    Charge

    CALCULATEBASIC

    RENTALCHARGE

    0- '::--0 GesollneCustome;--" ChargeRentalRecord

    CALCULATEGASOLINECHARGE

    Figure 5.1 Three unnecessarilystamp-coupled modules

  • 68 Coupling Chap. 5 Sec. 5.2 Normal Coupling 69

    01 STUFF02 PRICE-PER- ITEM02 NUMBER-OF- ITEMS02 DISCOUNT-TYPE02 SALES-TAX

    This idea of collecting unrelated data items into an artificial data structureis called bundling. Doing it offers you nothing but needless obscurity. Acommon sign that the data structure is not appropriate to the problem isits vague or meaningless name. People bundle data because they thinkthat doing so somehow reduces coupling. However, introducing stamp

    Price Number r IPer Item \ of Items JStuffrTotal JTotal

    Discount, Sales~ Cost CostType Tax . ..

    CALCULATE CALCULATETOTAL TOTA L

    PURCHASE PURCHASECOST cost

    Figure 5.9 Figure 5.10

    Finally, unnecessary stamp coupling tends to expose a module tomore data than it needs , with possibly disastrous consequences. If a de-fect in VALIDATE PHONE NUMBER wrote garbage in the field UCENSENUMBER, how would you guess that you had to look in the phone-number part of the system for the defect?

    So, to sum up this warning, such injudicious stamp coupling broad-ens interfaces, introduces extra obscurity, and reduces flexibility. Again ,starve your modules of superfluous data!

    2. Look at the fragment of structure chart in Figure 5.9 . Could we replacethose four parameters by a single structure? A possible solution is to use adata structure called, for example, STUFF, shown in Figure 5.10. In CO-BOL, for example, STUFF might be defined by

    Figure 5.11 Two conlrol-coupledmodul es

    lTransRecord

    MATCHCUSTOMER

    RECORDS

    What!To Do 1MasterFlag Record

    SYSTEMINPUTI

    OUTPUTCONTROL

    coupling for the sake of bundling has as much therapeutic effect as abandaid on a pimple.

    5.2.3 Control Coupling

    Two modules are control coupled if one passes to the other a piece of informa-tion intended to control the internal logic of the other. Figure 5.11 shows twocontrol-coupled modules.

    The value of WHAT TO DO FLAGindicates to SYSTEMINPUT/OUTPUTCONTROL which record(sJ to read. For example, Value 1 means GET NEXTMASTER RECORD; Value 2 means GET NEXT TRANS RECORD; Value 3means GET BOTH; Value 4 means PRINT PAGE HEADINGS; and so on.

    In Figure 5.11 , MATCH CUSTOMER RECORDSexplicitly decides whichpart of the logic of SYSTEM INPUT/OUTPUT CONTROL to use. In order forthe calling module to make such a decision, it must know how the logic of thesubordinate called module is organized. For example, in order to choose theright value for WHAT TO DO FLAG, MATCH CUSTOMER RECORDS mustknow the logic of SYSTEM INPUT/OUTPUT CONTROL.

    All this leads to some indirectness and obscurity. However, after havingstudied a large number of modules, I've concluded that control coupling is notof itself a great problem. The reason it 's lowest on the totem pole of normaltypes of coupling is that it often indicates the presence of other, more grue-some, design ills.

    Just as the virulent tropical disease of lurgi is presaged by a small blacksp ot on the victim's nose , so too are the design diseases of poor cohesion,program inversion, being input driven, and decision splitting often revealed bythe presence of a controlllag between modules. Thus , the best way to removecontrol coupling is to attack the design problems that cause it. (These designproblems are discussed in Chapters 6 and 7.J

    Figure 5.B

    This Module Couldn'tCare LessAboutGasUsed

    1Phon.NumberIs ValidVALIDATE

    PHONENUMBER

    CustomerIRentalRecord

  • 70 Coupling Chap. 5 Sec. 5.2 Normal Coupling 71

    A Dire Warning

    control flag. The second type of flag was used to describe a piece of data,namely, the ACCOUNT NUMBER). This type of flag is called a descriptiveflag. It is virtually harmless.

    By now, you might feel a little confused about the difference betweendata, descriptive flags, and control flags. The clue to the distinction is invari-ably in the name of the piece of information. Data are named by nouns, de-scriptive flags by adjectives, and control flags by verbs, as shown in Table 5.1.

    Data usually record quantities or amounts that relate directly to the prob-lem. Descriptive flags usually describe data or a situation that has occurred;they are one step removed from the problem. Control flags usually indicatesome particular quirk of the implementation and, consequently, bear no rela-tion to the problem whatsoever. You shou ld therefore strive to remove controlflags wherever you possibly can-usually by curing the design maladies thatcause them.

    If a control flag passes downward from a boss to a subordinate, the bossmust know something of the internals of the subordinate. (The subordinate issaid to have low cohesion; it is not a black box.] If the control flag headsupward from subordinate to boss, then another kind of faulty partitioningappears-inversion of authority, which means that a subordinate gives ordersto its bass.

    In Figure 5.12, FIND CUSTOMER NAME tells PRODUCE CUSTOMERPAYMENT REPORT to print an error message whenever a particular accountnumber cannot be found. This makes a mockery of hierarchy; it 's equivalent toa worker 's saying: "Boss, do this ," or "Boss, don't do that:' Another problem isthat FIND CUSTOMERNAMEassumes that whatever module calls it is capableof writing error messages.

    The partitioning could be improved in either of two ways. First, if report-ing an error is really a part of the function of finding a CUSTOMERNAME, thenFIND CUSTOMERNAME should write the error message. Second, FIND CUSTOMER NAME may not really know that an error has occurred. The boss maybe able to correct the error in some way unknown to the subordinate. In thiscase, the subordinate module should just report that no such account numberwas found , as shown in Figure 5.13.

    In this section on control coupling, we've seen that a flag being passedfrom one module to another for the purp ose of control signifies poor partition-ing. A function has been split between the two modules , a module has to beaware of the detailed internal logic of its subordinate, or a module has to beaware of the specific capabilities of its boss (an inversion of authority].

    However , we've also seen that not all flagsare equally bad. A flag namedWRITE 'NO SUCH PERSON' ERROR MESSAGE was deemed undesirable,whereas a flag named ACCOUNT NUMBER IS INVALID was deemed accept-able. The difference between the two flags is that the first was used to explic-itly tell a receiving module what it has to do. This type of flag is called a

    TABLE 5.1

    Type of Type ofinformation Depicted by name

    Data C>-+ Noun

    Descriptive flag ..... Adjective

    Control flag ..... Verb

    Exampl es

    PriceofeggsAgeZip codeEgg Is rott enZip code Is numericTransaction file is at endRead next recordReject this customerRewind master file

    ' Yourdon and Constantine (1978) use the term hybrid coupling for what is essentiallyCOBOL's ALTER statement. I define the term here in agreement with its current usage. For acomprehensive discus sion. see Yourdon and Constantine. 1978 .

    I now have to discuss a very painful topic: the way that some social misflts goabout hiding all kinds of flags within perfectly innocuous pieces of data thatnever did anybody any harm. This is the phenomenon of hybrid coupling,which results from the assignment of different meanings to different parts ofthe range of a piece of data.' If a piece of data were an animal , then hybridcoupling would result in a creature having the front end of a gnu, the back endof a camel, and the kidneys of a rhino. (Hybrid coupling is so odd that I neverknow where to place it in the book. By tradition, however, it goes with controlcoupling.)

    The following is an example of hybrid coupling from the Electric GruntBook Co. (EGB). Although I've simplified it a great deal, it still retains itsoriginal odious character.

    1AccountNumberIs Invalid

    FIN DCUSTOMER

    NAME

    Figure 5.13

    customerlAccount tCustomerNumber bNamel Wriler 'No SuchPerson'Error Message

    PRODUCECUSTOMERPAYMENTREPORT

    ustomerrl customecountumber Name

    FINDCUSTOMER

    NAME

    CAcN

  • 72 COUplin9 Chap. 5 Sec. 5.3 Common (Alias Global) Coupling 73

    The EGB Co. is a mail-order company whose customers were assigned accountnumbers of five digits, ranging from 00U01 to 99999. However, there were somerather peculiar account numbers. For instance, those in the range 90000-90999were not account numbers at all! They werehidden pieces of control informationthat meant "mail a piece of literature to the region represented by the last threedigits." Those customers with account numbers in the range 91000-91999 had aspecial status. They were allowed an extra 30 days in which to pay their bills.The full range of an EGB account number is shown in Figure 5.14.

    Hybrid coupling, in a sense, does narrow the interfaces between mod-ules. But it introduces such indirectness, murky obscurity, and-as we saw atthe Electric Grunt Company-suc h ghastly inflexibility that it can bring sensi-ble maintenance to a grinding halt. If, after this warning, you still insist onusing hybrid coupling, then all I can say is: Maya thousand angry scorpionsinfest your cubicle!

    Section 5.2 examined data, stamp, and control coupling, which-for better orworse-retain the basic spirit of modularity. Sections 5.3 and 5.4 examinetypes of coupling that stray outside the bounds of good modularity.

    Two modules are common coupled if they refer to the same global dataarea. In Figure 5.15, FIND PART NAME and REMOVE STOCK are commoncoupled because they both refer to the same global area , which contains (proba-bly among other data) PARTS TABLE and ERROR FLAG3.'

    The term common is taken from FORTRAN's COMMON, the area that canbe accessed by any SUBROUTINE or FUNCTION. However, globally accessi-ble data areas can be created in most languages. In PLlI, global data is createdby the use of the EXTERNAL attribute; in COBOL, a DATA DIVISION in itsentirety is global to any paragraph in the PROCEDURE DIVISION.

    Comm on coupling is bad for seven reasons. First, a defect (or program-mer ma lpractice!) in any module using a global area may show up in any othermod ule using that global area because global data doesn't reside in the protec-tive haven of a module. A common area is a jungle in which a piece of datamay be pounced on and mang led at any moment.

    Second, modules that refer to global data usually do so by explicit name;For example, a telephone number editing module might receive its telephonenumber from a globa l piece of data called TEL NO. That module is now com-mitted to the name TEL NO; it can't edit a telephone number that is calledsomething other than TEL NO, either elsewhere in this system or in otherapplications. Only if you 're lucky enough to find an application with a TELNO can you use this module. By contrast, modules called by parameters aren'ttied to specific names in the outside world. The programmers of such modulescan pick whatever names they want, thereby freeing them for any particul~context or usage. In other words , the flexibility of globally coupled modules ISmuch worse than that of normally coupled ones .

    Third, common coupling introduces an odd kind of remoteness into asystem: remoteness in time. A module (say, A) in a system may leave a value ina piece of data, X, in a global area and a long , long time later another module(say, B) will pick up that value. A maintenance programmer studying B mayspend a lot of time wondering when and how X got its value.

    Fourth, global areas may sometimes be drastically abused, as , for instance,

    5.3 COMMON (ALIAS GLOBAL) COUPLING

    99999

    I

    Special 90XXX RangeMeans Mail LiteratureTo Whole Region

    / 91000 91999

    I II I---~90000 90999 \

    Sp ecial 9 1XXX f;:tangeMeans Extra Credit Period

    00001Account l --- ---I-~----'~-...,....-NUmber~

    NormalRange

    As far as I could tell, the supreme benefit of the scheme shown in Figure5.14 was that it saved a few bytes of storage in the whole system-a byte ofcontrol information for mailing literature, a couple of bytes for the region, and abyte for the credit rating.

    The maintenance changes that exposed the grotesque nature of these so-called account numbers were as follows. Some customers were to be given aspecial trade discount. Yes, you guessed it. They were made the 92000 gang.About two days later, it was realized that several of the customers eligi ble forthe special trade discount also were eligible for the additional 30-day creditperiod. A few quick-and-dirty changes were made to the code, and these peo-ple were issued numbers in the 93000-93999 range . As years and personnelwent by , business boomed. The highest account number, which had been30000 for some years, rea ched 8900 0, threatening to enroach on the accountnumber range that signified mailing literature. But the new Manager of Ac-count Numbers was unaware of the 90XXX convention , and since nobody likedhim, nobody told h im.

    Customer number 90000 was welcomed to the Electric Grunt Book Co.with a spectacular event. His bill for $9.57 was circulated to about 2,500 peo -ple in New Jersey. The cost of rescinding that bill was huge, especially sincesome people actually paid $9.57 for goods they had neither ordered no r re-ceived!

    The EGB Company's solution to that little problem was twofold. Themanager of account numbers was fired for "glaring incompetence," and 94000was skipped to as the next available account number. The ridiculous schemewas finally abandoned when the l ,OOlst special credit customer arrived andthere was no available account number for him. To restore sanity requiredsurprisingly extensive and expensive modifications to the code.

    Figure 5.14 This is ad hoc notation, nottypical\y used in Structured Design.

  • 74 Coupling Chap. 5 Sec. 5.3 Common (Alias Global) Coupling 75

    A GlobalArea

    when different modules use the same area to store quite different pieces ofinformation. In Figure 5.15, ERROR FLAG3 may mean "insufficient stock," or"no such part number," depending on which module used it last. Because ofthis extra obscurity, maintenance efforts-especially debugging-become ashairy as a werewolf's handshake.

    Fifth, programs with a lot of global data are extremely tough for mainte-nance programmers to understand because it's difficult to know what data areused by a particular module. It's especially hard to tell what the actual cou-pling is between any pair of modules, since one has to ascertain what data, ifany, are shared. Actual coupling is hidden among potential coupling just as aleaf might be hidden in a forest. This leads to obscurity. The true breadth ofmodule interfaces is far from clear . I can depict the tangle of this obscuritydramatically in Figure 5.16.

    The expense of untangling this skein of interconnections is very real. Infact, one of the major technical problems of OS/360 and its offspring operatingsystems OS/vSl and OS/vS2 was that thousands of modules had access tolarge global areas called "task control blocks" (Myers, 1978).

    Sixth, just as it's difficult to discover what data must be changed if amodule is changed, it is also difficult to find out what modules must bechanged if a piece of data is changed. But it 's important to find out . For in-stance, if a piece of data in a global area has to be changed from five bytes tonine bytes , several modules will be affected. But which? Without a cross-reference listing, you must check every module in the system. This remotenessagain consumes time and therefore money.

    The seventh reason that common coupling is undesirable applies specifi-cally to FORTRAN. In that language, modules refer to data in COMMONnot byname but by location relative to the beginning of the COMMON block. Forexample, a COMMON block may contain A, B,and C. If a SUBROUTINE wantsto access C, it must know how big A and Bare in order to get the right offset. IfA changes its length, the SUBROUTINE will have to be changed, whether or not

    Figure 5.16. Brain Teaser: Who's joined to whom-and by what?

    GFEo

    it refers to A! This inflexible feature compounds common coupling with a kindof stamp coupling among unrelated global items and explains why seeminglytrivial changes to some FORTRAN programs have the maintenance program-mer busily duplicating a particular COMMON line 39 times-once for each 'SUBROUTINEusing that COMMON.5

    Modularity calls for constraining a particular item of data as much aspossible to a single module or at most to a small group of modules. The use ofcommon data degrades this idea of modularity by allowing data to stray outsidethe strict limits of a module."

    COBOLis not particularly strong in this respect. Neither a SECTION nora PARAGRAPH makes a very self-contained module, since, unfortunately, thewhole of the DATA DIVISION is wide open to the use or the abuse of anySECTION or PARAGRAPH in the PROCEDURE DIVISION. The best way toachieve modularity in COBOL is by using CALLed programs. In that way, theinterface between modules can be restricted to the LINKAGE SECTION. If theLINKAGE SECTION isn't so wide that Ben Hur could drive a team of horses anda chariot full of bugs through it, then the coupling between the programs is keptlow.

    The use of small NAMED COMMON arees does largely allevlete this particular problem.Sectlon 7.8 shows a valld use for such small areas of global data shared between a few module s.

    aHowever. the use of constantdatain a common area in orderto reduceredundancyis oftenpermissible. Section 5.5 covers this topic.

    Figure 5.15 Common-coupledmodules

    ~ut OfStock

    REMOVESTOCK

    FINDPARTNAME

  • 76 Coupling Chap. 5 Sec. 5.4 Content (Alias Pathological) Coupling n

    A Foot note on Common Coupling: Database Coupling

    7 Chapter a shows that a well-designed database is, in fact, necessary to communicata infor-mation from one essential event (transaction) to another. However. use of a database to passinformation within a single tran saction is undesirable.

    Two modules exhibit content coupling if one refers to the inside of the other inany way-for instance, if one module branches or falls through into another, ifone module refers to (or changes) data within another, or if one module alters astatement in another. Such coupling makes nonsense of the concept of blackbox modules since it forces one module to know about the explicit contents andimp lementation of another one. On the whole, only assembler language allowsdesigners to indulge in such sick practices. MOst'good, Iii~er level language smake it difficuli to implement content coupling.

    One of the great rewards of writing a book is that it occasionally allows theauthor the opportunity to take revenge on those people who once made his lifemiserable. So, during the remainder of this section, I will wreak revenge uponWally, whose diabolical programs I was once forced to maintain.

    Wally was a designer with superlatively promiscuous bad habits. Youcould never be sure what death-defying stunt Wally's code would performnext. But one of Wally's favorite malpractices was content coupling, inall its variations. He was particularly fond of making his programs performbreathtaking leaps, Evel Knievel -like, from the mid dle of one moduleacross furlongs of code right into the middle of another module. Spectatorswere awestruck by these feats . But I, as the poor main tenance programmeroften left to pick up the pieces after an accidental calami ty, was far fromenthralled.

    A small sample of Wally 's code will show you what I was up against.

    tract large areas of the database. It creates, deletes, modifies, or reads only the'specific objects that it needs in order to carry out its function. This leads to anarrowness of database coupling among transactions that is not typical withcommon coupling! Furthermore, in a properly documented system, whichStructured Design facilitates, the coupling is made explicit to the system'smaintainers.

    Nevertheless, to make life as easy as possible for people trying to assessthe effects of cou pling via the database, I recommend that you do what you canto leave an audit trail of usage within the database itself. At the very least,include a recor d header in every record in the database. Then have everytransaction that creates or updates a record note its identity in the recordheader, along with the date, time, and perhaps terminal identification. If atransaction should abuse the database, its "fingerprints" would be all over therecord, and it could be taught the error of its ways.

    5.4 CONTENT (ALIAS PATHOLOGICAL) COUPLING

    "TRANSAC-TlON a"

    ust Reo7 \READ

    CUST RECFROM oa ,

    c

    Figure 5.17

    "TRANSAC-TIO NA"

    I Cust Rec'\WRITE

    CUST RECTO Oa

    Many systems comprise transactions. I cover this topic in Chapter 10. Usu-ally , these transactions write to and read from files, datasets, or databases.Therefore, a transaction A, which (say) writes a CUSTOMER RECORD to adatabase, will be coupled to a transaction B that reads data about a customerfrom that database. This coupling exists although it may not appear explicitlyon a structure chart. For example, in Figure 5.17 a defect in transaction A thatcreates erroneous data in the CUSTOMERRECORD might cause transaction Bto crash or to generate erroneous results.

    At first sight, database coupling seems to resemble common coupling,and, indeed, there are some similarities. The chief similarity is that a defect inany transaction using a piece of the database can be transmitted to any othertransaction using the same piece. Also, there may be a large rem oteness intime-weeks or even months-between the creation of the problem and itsdiscovery.

    However, database coupling also differs from common coupling in threesignificant ways . First, databases are nonvolatile. Their contents can be in-spected for correctness by, for instance, database auditing software. .Second,databases are (or should be!) designed with consummate discipline. They arenot arbitrary areas of data but contain well-defined, applicatlon-oriented ob-jects with spec ific integrity rules . This also facilitates validation: on writing,on reading, or on auditing. Third, a given transaction does not randomly at-.

  • ROUTINE A

    There were two assembler-language routines-let's call them A and B-asshown below:

    ules. Content coupling brings us back to the undisciplined mess of nonmodu-lar coding.

    I would love to hurl yet more invective at Wally for his other deviouspractices, such as the creation of a module that modified instructions in an-other module. But if you've ever tried to maintain a system sprinkled withALTERS, then you've already experienced this form of pathology to the point ofcriminality. No, it's time to move away from such distasteful mockeries ofmodularity to sum up the subject of coupling.

    79Determining Coupling TypeSec. 5.5Chap. 5Coupling78

    JUMP TO SRCH + 3525.5 DETERMINING COUPLING TYPE

    END ROUTINE A

    ROUTINE B:

    SRCH: MOVE 1 TO REGISTER 0

    ! --+

    Two modules may be coupled in more than one way. In that case, their cou-pling isilefinecl by the worst coupling type they exhibit."For example, if twomodules are-stamp iinacommon coupled, they are characterized as commoncoupled. They 're still stamp coupled, but that's outweighed by their commoncoupling.

    A good rule of thumb for designing the way a module gets and returns itsinformation is to imagine it as a library module. How would this module beeasiest to understand? How would this module be most usable to other peoplein the shop?

    Another way in which the coupling of a design can be evaluated is tosuppose that each module will be coded by a different programmer. Howindependently can the programmers work? What may change that may causechanges to multiple modules? Is there any way in which the effects of thechange could be isolated to one module? Answering these questions will de-termine which user changes are likely to require modifications to a large num-ber of modules.

    END ROUTINE B

    5.6 COMPARISON OF COUPLING TYPES

    The jump in routine A landed not at SRCHin routine B, but at SRCH+ 352bytes , appropriately marked by "I" This meant that routine A was inextricablyconnected to the internal details of routine B; I couldn't make a change to B (atleast between SRCH and " !"] without a major risk of causing an error in theoperation of A.

    Unfortunately, the whole system was similarly content coupled. It's noexaggeration to say that in order to change any line of code in the system , I hadto worry about every other line of code in the system. Pathological indeed!But there wasn't much that I could do about it. You see, Wally was myboss.

    The problem with content coupling is that it defies the principle of modu-larity. The maintainer of module B should have complete freedom to recodethe module in any way he sees fit, so long as it still carries out its black boxfunction. But if it is content coupled, then he has no freedom. He can't changeits algorithm; he can't even change label names without fouling up other mod-

    Table 5.2 reviews the specific qualities of each type of coupling.

    SUMMARY

    Coupling is the measure of the interdependence between two modules. In agood design, coupling is kept to a minimum by: eliminating unnecessary rela-tionships between modules; reducing the number of necessary relationships:and easing the tightness of necessary relationships.

    In sequence from best to worst, there are three broad categories of cou-pling between modules: normal coupling (coupling by parameters); global orcommon coupling (coupling via a globally accessible data area): and content orpathological coupling (coupling by direct connection between the internals ofmodules) . Again in sequence from best to worst, normal coupling may be: datacoupling (coupling by elementary parameters); stamp coupling (coupling by

  • 80 Coupling Chap. 5 Sec. 5.6 Comparison of Coupling Types 81

    TABLE 5.2

    Coupli ngtype

    DataTramp

    StampBundling

    ControlHybrid

    CommonContent

    Susceptibility Module'sto ripple usabilit y in

    effect Modifiebility Understandability other systems

    Variable" Good Good GoedPoor Medium Medium PoorVariable - Medium Medium MediumVariable" Medium Poor PoorMedium Poort Poort PoortMedium" * Bad Bad BadBad Medium Bad PoorBad Bad Bad Bad

    (e) CALL PRINT LABELS(in a language other than COBOL)

    AnswerThe coupling indicated by each of the interlaces given are(a) data(b) stamp(c) stamp (but presumably with superfluous fields being passed down)(d) stamp (but with the weirdest and most unnecessary case of bundling that I've seen

    for many a moon)(e) either common or content, if the language being used permits thes e forms of cou-

    pling .- Depends on lbe breadlb [the number of indivi dual items) of lbe interface.t Poor mainly because of concomitant problems in the interface and lbe cohesion of one of themodules.-- If the con ventio n used in the hybrid data has to be changed . lbe rip ple effect can be deva-stat ing.

    composite parameters); or control coupling (coupling by parameters used ex-plicitly to control the behavior of the recipient module).

    Other terms that I've used in this chapter are:

    tramp data: data that passes through modules that do not need itin order to reach the recipient module (to be avoided)

    bundling: the creation of an artificial, meaningless data struc-ture in order to disguise broad data coupling (to beavoided)

    hybrid coupling: the use of a convention in more than one modulewhereby a piece of data has different meani ngs indifferent parts of its range (to be avoided)

    The most flexible and maintainable designs are typically those with thesimplest interfaces between modules: the types of interfaces that you mightdesign for standard library modules.

    EXERCISE

    Whet type of coupling is indicated by each of the following interlaces from the callingmodule to a module that prints mailing labels?(a) CALL PRINT LABELl USING NAME, STREET ADDRESS, CITY, STATE, ZIP(b) CALL PRINT LABEL2 USING CUST MAIUNG ADDRESS(c) CALL PRINT LABEL3 USING CUST PURCHASE ORDER RECORD(d) CALL PRINT LABEL4 USING NZ, SAS , CITY .

    (where NZ = NAME + ZIPSAS = STREET ADDRESS + STATE)

    coupling001coupling002coupling003coupling004coupling005coupling006coupling007coupling008coupling009coupling010coupling011coupling012coupling013