Professional Documents
Culture Documents
\
Chap. 6 Cohesion 83 (
(
Sidtown Fredborough
Employeesof (
Factory for Better Mousetrap Co.
Better Mousetraps Live Here
(
(
Highway (
6 (
Figure 8.1
Zokko Soda Co.
( ;
(
course, thinly disguised modules, and the traffic between th em is coupling.
The term for " putting strongl y associated th ings in the same module" is cohe- (
sion, which brings us to this definition:
\
Cohesion is the measure of the strength of functional relatedness of elements (
within a module.
(
of bottles rumble from Fredborough to Sidtown to be filled with sparkling, low- ills of each of the types . The term itself was borrowed from sociology , where it
calorie Zokko soda. But what if these two companies rearrang ed their faciliti es means the relatedness of humans within groups. (
as shown in Figure 6.21 Now, each company has restricted itself to one city, From these early studies and later refinements, Stevens , Myers, Constan-
(
resulting in two very boring cities, but also- more importantly-resulting in tine, and Yourdon developed a scale of cohesion (Table 6.1) as a measure of the
little or no traffic between the cities. (There may be some traffic if Better black boxness of a module and , it turns out from experiments, as a good mea- (
Mousetrap workers occasionally pause to refresh th emselves with Zokko sod a.) sure of the maintainability of a module. (For referenc es, see Stevens et al
(1974) and Yourdon and Constantine (1978).) (
The moral of this tale of two cities is that putting strongly associated
thin gs in the same city reduces the traffic between the cities. The cities are, of 1 In fact. a common synonym for modul e cohesion is module strength. . l
82 (
(
(
(
( 84 Cohesion Chap. 6 Sec. 6.2 Sequential Cohension 85
(
Sidtown Fredborough Notice that each of these modules has a strong, single-minded purpose.
( Employees of When its boss calls it, it carries out just one job to completion without getting
Bottle Plant for BetterMousetrap Co. involved in any extracurricular activity. For example, DETERMINE CUS-
( Zokko Soda Co. LiveHere
TOMER MORTGAGEREPAYMENTmust do just that; it must not, for instance,
( print out page headings.
Some of these functionally cohes ive modules are very simple and would
( Highway
probably be found low on the structure chart (such as verify ALPHABETIC
( SYNTAX or READ TRANSACTION RECORD) , while others are complicated
and would be found quite high on the structure chart (for instance, COMPUTE
( No Traffic
POINT OF IMPACT OF MISSILE). READ TRANSACTION RECORD is obvi-
(
ously doing a single function, but how can CALCULATE NET EMPLOYEE
SALARYbe doing only one job when everyone knows that it's computing gross
( Soda Plantfor salary, FICA deductions, federal income tax, state income tax, and so on? The
Factory for
ZokkoSodaCo.
Better Mousetraps
point is thathowever complicated a module, and however many subfunctions
( makeup' its total job, 'if you can sum up everything that it accomplishes for its .
Figure 6.2 iJoss 'as one problem-related function, then that module is functionally cohe-
(
(
sive: 2
to uoderstand than its Inside (logic)," and "a good module Is easier to use than to write." (Holt ,
( Coincidental MAINTAINABILITY transparent box 1975.)
{
\
86 Cohesion Chap. 6 Sec. 6.3 Communicational Cohesion 87
These four activities are related because they all work on the same input data,
Raw '? Formatted the book, which makes the "module" communicationally cohesive. (
Record'
! Cross-validated
Record Another example of a communicationally cohesive module is
(
module determine customer details (
FORMAT
AND CROSS- use customer account no
VALIDATE find customer name \
RECORD
Figure 6.3
find customer loan balance (
return customer name , customer loan balance (
step , PUT ON FINAL COAT, we would have a functionally cohesive module endmodule
called REPAINT CAR.) To determine the "module's" level of cohesion, there- l
fore, we must ask: How are these activities related to one another? The answer In Figure 6.4, the two activities of finding the customer's name and find-
(
is that the output from one activity serves as input to the next -just like on an ing his loan balance use the input of CUSTOMER ACCOUNT NO. The cou-
assembly line. And that fits the definition of a sequentially cohesive module. pling between a communicationally cohesive module and its caller is usually
Here's another example of a sequentially cohesive module, described first acceptable; typically, it's narrow on one side and arbitrarily broad on the other,
in pse udocode and then shown on a structure chart. depending on the number of functions in the module. (
Communicationally cohesive modules are quite maintainable, although (
module format and cross-validate record there can be problems. In Figure 6.4, it's possible that another module in the
uses raw record system would need to find out a customer's name but wouldn't be interested in (
format raw record his loan balance. That module would either have to discard the loan balance (
cross-validate fields in raw record data (dirty and redundant coupling) or would need its own code for finding the
customer name (duplication of function). (
returns formatted cross-validated record
Another potential problem with a communicationally cohesive module is
endmodule (
the temptation to share code among the activities within it; that can make it
tough to change one activity without destroying another. For example, the (
In Figure 6.3, the output from the first activity (formatting) is the input to
upper module in Figure 6.5 is communicationally cohesi ve. With EMPLOYEE
the second (cross-validation). (
SALARYTABLE, it both generates a report on all of the employees' salaries and
A sequentially cohesive module usually has good coupling and is easily
calculates their average salary. Because both functions need access to every (
maintained. Indeed, it is almost as maintainable as a functionally cohesive
salary, a programmer may be tempted to put them inside the same loop . It's
module. The only real disadvantage of a sequentially cohesive module is that (
it is not so readily reusable in the same system (or in other systems) as is a
functionally cohesive module, because it contains activities that will not in
general be useful together.
Emp Ioyee
Salary
Table
r! Average
Salary
l
(
PRODUCE
EMPLOYEE (
6.3 COMMUNICATIONAL COHESION SALARY REPORT
Customer ANDCALCULATE (
A communicationally cohesive module is one whose elements contribute to ! Loan
Balance
AVERAGE
SALARY
activities that use the same input or output data.
Suppose we wish to find out some facts about a book: For instance, we
customer,
Account
No ot Customer
Name
Emplayee
Salary Report
OetaiI,
r (
(
may wish to
(
DETERMINE
1. FIND TITLE OF BOOK CUSTOMER (
WRITE
2. FIND PRICE OF BOOK DETAILS
1
Record .
( Account
t Customer Account
6 Name Account Loan Record
No
b Loan No No Balance
( Balance
and
( FORMAT AND CROSS-VALIDATE RECORO
OETERMINE FIND CALCULATE Module IsSequentially Cohesive
CUSTOMER
( CUSTOMER CUSTOMER
LOAN
OETAILS NAME
BALANCE
(
Employee
{ Salary
Figure 6.6 Table
(
possible, however, that at some later date a report on only the first 20 employ-
( ees might need to be generated. To generate this new report, a maintenance
programmer would need to change CALCULATE AVERAGE SALARY by in-
( serting a test in the loop to determine when the 20th employee had been PRODUCE EMPLOYEE SALARY REPORT
AND CALCULATE AVERAGE SALARY
( passed. However, a better solution would be to create a separate loop for each ModuleIs CommunicationallyCohesive
activity. But in that case , there would no longer be any point in keeping the
( Figure 6.7
two activities in the same module.
( Almost always, you'll improve maintainability if you split a communica- modules of the middle levels of cohesion. A procedurally cohesive module is
tionally cohesive module into separate, functionally cohesive ones, as in Figure one whose elements are involved in different and possibly unrelated activities
( 6.6. in which control flows from each activity to the next. (Remember that in a
Modules with communicational and sequential cohesion seem similar sequentially cohesive module data, not control, flows from one ~ctiVity to the
(
since they both contain activities organized around the data in the original next.) Here is a list of steps in an imaginary procedurally cohesive module.
( problem. They also have quite clean coupling, because few of their elements
are related to elements in other modules. The main difference between them is 1. CLEAN UTENSILS FROM PREVIOUS MEAL
( that a sequentially cohesive module operates like an assembly line; its individ-
2. PREPARE TURKEY FOR ROASTING
( ual activities must be carried out in a specific order. But in a communica-
tionally cohesive module, order of execution is unimportant. In th e module 3. MAKE PHONE CALL
( depicted in Figure 6.5, it doesn't matter whether the employee's report is gener- 4. TAKE SHOWER
( ated before, after, or at the same time as the average salary is calculated. 5, CHOP VEGETABLES
Sequentially and communicationally cohesive modules can be illustrated 6. SET TABLE
in data flow terms , as shown in Figure 6.7. This illustration highlights the fact
that the activities are strongly related by the data in the problem. Chapter 8 SET TABLE is the last step listed for this "module," But GET DRESSED or
( MAKE ANOTHER PHONE CALLwould be equally valid candidates for step 6,
will examine the partitioning of a system by means of a data flow diagram.
( Chapter 10 will look at the strategy of transform analysis, which is used to because the activities on this list are related only in that they may well happen
derive a good structure chart from a DFD. We'll see that this strategy tends to in this order during a particular day. They make up a piece of someone's daily
( produce modules of the top three levels of cohesion. If you don't mind my flowchart. They are related by order of execution rather than by any single
( making a slight forward reference to the DFD, I can depict sequential and problem-related function.
communicational cohesion in data-flow terms as shown in Figure 6.7. Another example of a procedurally cohesive module is shown in Figure
( 6.8 as part of a structure chart.
Procedurally cohesive modules tend to be composed of pieces of func-
( 1l.4 PROCEDURAL COHESION tions that have little relationship to one another (except that they're carried out
( in a specific order at a certain time). However, these pieces of functions proba-
As we reach procedural cohesion, we cross the boundary from the easily main- bly have quite a lot to do with pieces of functions in other modules. WRITE,
( READ, AND EDIT SOMEWHAT finishes dealing with the last transaction (by
tainable modules of the higher levels of cohesion to the less easily maintainable
(
90 Cohesion Chap. 6 Sec. 6.5 Temporal Cohesion 91
(
The effect of the module depends on the value in INPUT FLAG: 6.7 COINCIDENTAL COHESION
(
A coincidentally cohesive module is one whose elements contribute to activi-
when INPUT FLAG = 1 ties with no meaningful relationship to one another; as in
RECORD-A is written to NEW MASTER FILE
(
RECORD-B is set to the next TRAN FILE1 record 1. FIX CAR
RECORD-C is undefined (
2. BAKE CAKE
when INPUT FLAG = 2 3. WALKDOG (
RECORD-A is used as an auxiliary input flag 4. FILL OUT ASTRONAUT-APPLICATION FORM (
RECORD-B is set to the next TRAN FILE1 reco rd 5. HAVE A BEER
(But only if RECORD-A had been set to SPACES; 6. GET OUT OF BED
otherwise RECORD-B is undefined) 7. GO TO THE MOVIES (
RECORD-C is set to the next TRAN FILE2 record
when INPUT FLAG = 3 A coincidentally cohesive module is similar to a logically cohesive one.
Its activities are related neither by flow of data nor by flow of control. (One (
RECORD-A is set to th e next MASTER FILE2 record
glance at the above list should convince you that you 'd be unlikely to carry out
RECORD-B is set to the next TRAN FILE1 record all seven activities at one time!) However, the activities in a logically cohesive [
RECORD-C is set to the next MASTER FILE1 record module are at least in the same category ; in a coincidentally cohesive module, (
*/ even that is not true.
The pseudocode and structure chart in Figure 6.12 will illustrate why <. \
coincidental cohesion is considered to be the worst level of coh esion. ( \
If you understand this module, then you're doing better than I did when I If you think that the module shown in Figure 6.12 has very little going for
had to maintain it. But let's see how you fare with a few changes. (
First, can you modify GENERAL 10 ROUTINE so that if INPUT FLAG = 3, module miscellaneous functions
uses func nag, operator message (
TRAN FILE2 instead ofTRAN FILE1 is read? Sorry, can't do it. A TRAN FILE2
updates rnatnurn, acc
record (120 chars] won't fit into RECORD-B (80 chars], into which the TRAN define trans record as 80 char
FILE1 record is currently being plac ed. RECORD-C (120 cha rs], which would define error switch as switch
fit, is already in use for the MASTER FILE1 record. if func nag - 1
Can you change the module so that if INPUT FLAG = 2, RECORD-C is then clear matnum to 0 r matnum is a matrix .,
written to NEW MASTER FILE? No go, I'm afraid. Remember that RECORD-C set ace to 1
is being used as a funn y flag when INPUT FLAG = 2? It can 't be used to hold etself func nag - 2
"real" information. then rewind tape-B (
Is it possible to lengthen a TRAN FILE2 record (120 chars] to 132 ch ars? I print customer headings Operator
hate to be difficult , but whe re on earth would we put it? The only possibility is elseif func nag - 3 Message Q (
Func t t Trans
RECORD-A (142 chars) with a lO-space padding (ugly). but we can't even do then rewind tape-B Flag T
6 Record (
~::nT ~
that because RECORD-A is being used for so many oth er weird things. elseif func nag - 4
• Error
The only reason that peopl e create logically coh esive modules is to over- then read trans record • Switch (
lap parts of functi ons that ha pp en to have the same lin es of cod e or the same ifeof
then set error switch to on (
buffers-but are not even execut ed at the same time! You can imagine, I'm
endlf (
sur e, that if code as well as buffers had been shared in the above example , the else display operator message MISCELLANEOUS
result would have been functions so inextricably int ertwined that Harry FUNCTIONS
endi' ( I
Houdini him self would ha ve had difficulty untangling them. And if nothing return trans record, error switch
can be overl app ed between functions, then logically cohes ive modules have no endmodule (
point whatsoeve r. A better name for logical cohesion would be illogical cohe-
Figure 6.12 (
sion!
(
\
(
(
(
( Sec. 6.8
96 Cohesion Chap. 6 Determining Module Cohesion 97
(
it, you are absolutely right. All the nasty things I described about logically particular module? One good way is to write a short sentence that accurately,
( honestly, and fully names the module and describes its function. Usually, the
cohesive modules hold true for coincidentally cohesive modules, and then
( somel structure of the sentence reveals fairly accurately the level of cohesion of the
module.
( For instance, if, while you were attempting to debug a piece of code, you
saw a call to a logically cohesive module like this Let's take a look at some examples:
( Functional cohesion. A module doing one function can be summed up by a
CALL GENERAL 10 ROtrrINE USING 3 , RECORD-A, RECORO-B, RECORO-C
.tJ
'.'
precise verb-object name ; for example,
(
( you'd at least get the feeling that it was doing some kind of input and/or output,
and you might be able to continue debugging without having to look at the Strong imperative verb Specific singuiar direct object
( actual code of GENERAL 10 ROUTINE. But if you stumbled across the follow-
READ CUSTOMER TRANSACTION RECORD
( ing call while doing midnight maintenance, you might think you were asleep
CALCULATE NORMAL AUTO iNSURANCE PREMIUM
and having a nightmare:'
( DEDUCT FEDERAL TAXES
CALL MISCELLANEOUS FUNCTIONS USING 4, BLANKS, DUMMY I , DUMMY 2 ,
( TRANS RECORO, ERROR SWITCH
( Sequential cohesion. A number of assembly-line functions show sequential
The only way you could possibly figure out what's going on is to dig down cohesion, as in
( among the actual code of MISCELLANEOUS FUNCTIONS and work out just
( which activity the module is carrying out on this occasion. MISCELLANEOUS VALIDATE TRANSACTION AND (USE IT TO) UPDATE MASTER RECORD
FUNCTIONS, like all coincidentally cohesive modules, is a joke module, a
( white box whose insides are glaringly visible. Such modules make systems Communicational cohesion. A number of nonsequential functions working on
(
less understandable and less maintainable than systems with no modularity at the same data are the clue here; for example,
aIll
( Coincidental cohesion, fortunately, is rare. Among its causes are the mis- CALCULATE AVERAGE AND MAXIMUM EMPLOYEE SALARY
guided attempts of morons to save time or memory (both usually unsuccessful);
(
the shoveling of existing monolithic code arbitrarily into modules; and the iII- Procedural cohesion. Look for procedural or "flowcharty" names; for example,
( considered maintenance changes to modules with mediocre (typically tempo-
ral) cohesion, leading to the addition of flags. LOOP ROtrrINE or SWITCH MODULE
( Logical and coincidental modules are similar in their schizophrenia.
( Such modules have no well-defined function, so the boss module must send a or, in worse cases, even less meaningful names.
completely artificial flag to tell them what to do. This violates the principle of Temporal cohesion. Time-related names are a giveaway; for example,
( independent black boxes, since the boss needs to know the internal details of
the subordinates. The coupling to both kinds of module is horrendously ob- START UP, END OF JOB, or BEFORE ...
(
scure because of the use of a single parameter for multiple purposes.
( Both logical and coincidental modules are such white boxes that to distin- Logical cohesion . The name is an umbrella or general-purpose one; for exam-
guish between them is quite subjective. But you could say that a coincidental ple ,
( module is a box of a whiter shade of pale.
( INPtrr ALL or EDIT MODULE
( 6.8 DETERMINING MODULE COHESION and to use the module, a flag is needed.
( Coincidental cohesion. The name is silly or meaningless; for example,
This chapter has defined, described, and given examples of each level of cohe-
( sion. But how do you actually set about determining the level of cohesion of a FRUNK-MODULE, PROCESS-ROUTINE , ROtrrINE-X9721-p
( • Note: This is Intended to Illustrate lousy code: it is not an example of correct COBOL and to use the module, a flag is needed.
syntax.
(
(
(
98 Cohesion Chap. 6 Sec. 6.10 Finding the Level of Cohesion 99 (
However, what about the case of a module called GET RECORD, FORMAT (
L.eveI of Cohesion
IT, AND EDIT IT? This appears to indicate that the module is sequentially (
1. Functional
Canthe Module
cohesive. But if it's renamed GET VALID RECORD, it suddenly appears to be
functionally cohesive, because all those activities make up the single problem- ( .
BeConsideredTo
related function of getting a valid record . But the same chains-in-parallel rule (
Be Doing One ?:Yes 2. Sequential applies. The best that we can say of this module as a whole is that it's function-
Probl em-related IsSequence (
function? No lmpcrtentf ally cohesive.
What Relates ~ata No 3. Communicational The leve l of cohe sion of a module depends on the activities it carries out
(
the Activities for its boss and is independent of where the modu le appears on the structure
With in the
Module? chart. For example, see Figure 6.14. There is normally not any tradeoff be- (
tween cohesion and coupling; they work together. Better (more) cohesion
(
~
4. Procedural
Flow of Is Sequence leads to better (less) coupling, which leads to better (more maintainable) sys-
Control Important? No 5. Temporal tems . (
\
(
(
(
( Comparison of Levels of Cohesion
100 Cohesion Chap. 6 Sec. 6.11 101
(
TABLE 6.2
( Customer9 Customer
Account. t Customer t Loan Cleanli-
( Number 0 Name b Status ness of Effect on
t Customer Cohesion Imple- Und erstand- overall system
level Coupling mentation Modifiability ability maintainability
Customer Q bName A Communicatlonally
+ t Customer
( Account
Number o Loan
,..-_ _ ' -_;;..;;Status
DETERMINE
CUSTOMER
Cohesive Module
Halfway Up
Functional Good Good Good Good Good
a StructureChart Sequential Good Good Good Good Fairly good
( DETA ILS
Communicational Medium Medium Medium Medium Medi um
( DETERM INE Procedural Variable Poor Variable Variable Bad
CUSTOMER
DETA ILS Temporal Poor Medium Medium Medium Bad
(
Logical Bad Bed Bad Poor Bad
( A Communicationally Coincidental Bad Poor Bad Bad Bad
Cohesive Module
( at the Bottom
of a Structure Chart
(
FINO EVALUATE
( CUSTOMER LOAN
NAME STATUS
(
I
( Each of These Functionally
Cohesive Modules Is at
the Bottom of a Structure
( A Functionally Cohesive
Module Very High
In a StructureChart
(
i"C Coincidental
( .~
..
0-
( .~
r::
(
.'go"
(
"
lL
<;
( GET GET GET GET
RANGES
~
r::
ELEVATION TIMES AZ IMUTHS
( "o
~
( Temporal
Procedural
(
I
Figure 6.14
(
( these seven levels are: functional (elements contribute to a single , problem-
related activity); sequential (activities within the module are connected in that Communicational
( the output from one serves as the input to another) ; communicational (activi- Logical
Sequential
( ties share the same input or output); procedural (activities share the same
procedural implementation); temporal (activities can,be carried out at the same Functional
( time) ; logical (activities appear to belong to the same general category); coinci- Level of Cohesion
( dental (activities have no relationship to one another) .
The maintainability of modules with functional, sequential, and com- Figure 6.15
(
(
(
102 Cohesion Chap. 6 (
EXERC ISE