You are on page 1of 11

(

\
Chap. 6 Cohesion 83 (

(
Sidtown Fredborough
Employeesof (
Factory for Better Mousetrap Co.
Better Mousetraps Live Here
(
(
Highway (
6 (

Heavy Tra ffic


(

Soda Plant for Bottl e Plant for (


Cohesion Zokko Soda Co.

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.
(

Element means an instruction, a group of instructions, a data definition or a call {


As we saw in the previous chapter, an important way to evaluate the partition- to another module; that is, any piece of code that accomplishes some work or
ing of a system is by how cleanly the modules are separated from one another. defines some data. l
That is th e criterion of coupling. Another way to determine partitioning is to Designers should create strong, highly cohesive modules, modules whose (
look at how the activities within a single module are related to one another. elements are strongly and genu inely related to one another.' On the other
This is the criterion of cohesion. Since coupling and cohesion are both ways of hand, the elements of one module should not be strongly related to the ele- (
measur ing partitioning, you 'd expect th em to be interdependent. Ind eed, they ments of another module, because that would lead to tight coupling between
(
are, in that the cohesion of a module often determines how tightly it will be the modules.
coupled to other modules in a system . Cohesion, then, is the second way to tell how well we've partitioned a
As an illustration, look at the map of a pair of cities in Figure 6.1. The system into modules. Indeed, making sure that all modules have good cohe-
sion is the best way to minimize coupling between th e modules. It also ensures (
heavy traffic betwe en Sidtown and Fredborough arises because of th e way in
whi ch the Better Mousetrap Company and the Zokko Soda Company have that the functions of the system reflect the functions of the original problem. (
distributed themselves. Every morning, Better Mousetrap workers leave the ir The idea of cohesion carne to Larry Constantine in the mid-1960s (Your-
don and Constantine, 1978, pp. 95-126). He was interested in learning wh y (
homes in Fredborough and beat a path to the door of the Better Mousetra p
factory in Sidtown . In the evening, they all return. Day and night, trucks full people create certain types of modules and in examining the relative merits and ( )

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

Systems built chiefly of normally coupled, functionally cohesive modules


Sections 6.1 to 6.7 will show the good and bad characteristics of each
( are by far the easiest (and thus cheapest!) systems to maintain. It is tempting to
level of cohesion.
think that any module can be summed up as performing one function , but don't
( be fooled. There are many kinds of modules whose bosses regard them as
doing different jobs that connot be summed up as a single problem-related
( .1 FUNCTIONAL COHESION function. The crucial factor in deciding the level of cohesion of these nonfunc-
( tional modules is how the different activities they perform are related to one
A functionally cohesive module contains elements that all contribu!.e..!.l?,.the , another.
( execiiticln 'of one and only one problem-related task. Examplesoffunctionally
cohesive modules are .
l
6.2 SEQUENTIAL COHESION
( COMPUTE COSINE OF ANGLE
( VERIFY ALPHABETIC SYNTAX A sequentially cohesive module is one who se elements are involved in activi-
READ TRANSACTION RECORD ties such that output data from one activ ity serves as input data to the next. To
( DETERMINE CUSTOMER MORTGAGE REPAYMENT illustrate this definition, imagine that you 're about to repaint your bright orange
Corvette a classy silver color. The sequ ence of steps might be something like
( COMPUTE POINT OF IMPACT OF MISSILE
this:
( CALCULATE NET EMPLOYEE SALARY
ASSIGN SEAT TO AIRLINE CUSTOMER 1. CLEAN CAR BODY
(
2. FILL IN HOLES IN CAR
( TABLE 6.1 SCALE OF COHESION 3. SAND CAR BODY
( BEST
4. APPLY PRIMER
Functional MAINTAINABILITY Black box
( Sequential Not-quite- This group of four activities cannot be summed up as a single function,
Communicational so-black box which means the "module" is not functionally coh esive . (If we added a fifth
(
(
Procedural
Temporal
Logical
1
WORST
Gray ·'
box !
White or
:l This is anoth er way of s tating the rules: "The outside (function) of a good module is easi er

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

3. FIND PUBLISHEROF BOOK (


4. FIND AUTHOR OF BOOK Figure 6.4 Figure 6.5 l
(
(
( 89
88 Cohesion Chap. 6 Sec. 6.4 Procedural Cohesion
(
(
ot Customer
Formatted
Customer, Name
Customer! t Customer Customerr Customer Raw Cross-validated

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

module write read and edit somewhat


uses out record
oI
R~ord
r Partially
t ~dited
bin
This piece of coding has tied table-A and table-B together, although the
tables are unrelated in the original problem. As an exercise in maintenance, I
write out record . Record leave it to you to figure out what to do to the module in Figure 6.9 if the length
read in record of table-B changes to 120 or if the elements in table-B become in some way
pad numeric fields or in record with zeros WRITE . dependent on table-A-avg.
return in record READ.
AND EDIT
endmodule SOMEWHAT
6.5 TEM PORAL COHESION (
Figure 6.8
A temporully cohesive module is one whose elements are involved in activities (
writing OUT RECORD) and starts to deal with the next one (by reading and that are related in time. Picture this late-evening scene:
somewhat editing IN RECORD) . It's typical of a procedurally cohesive module l
that the data sent to it and the data it sends back have little relationship. It's 1. PUT OUT MILK BOTTLES (
also typical that such a module passes around partial results (e.g., a partially 2. PUT OUT CAT
edited IN RECORD), flags, switches, and so on. (
3. TURN OFF TV
Section 6.3, on communicational cohesion, showed an example of a tricky (
4. BRUSH TEETH
programmer using a single loop to do two distinct activities: to compute em-
ployees' salaries and to report them . With procedural cohesion, such nasty (
These activities are unrelated to one another except that they 're carried out at a
tricks become rife-and often with no basis whatsoever in the problem itself. (
particular time . They're all part of an end-of-day routine.
As an example, look at Figure 6.9, which shows a procedurally cohesive mod-
The classic example of temporal cohesion is an initialization module; as (
ule that averages two completely unrelated tables, TABLE-A and TABLE-B,
which both just happen to have 100 elements each. shown in Figure 6.10. Temporally cohesive modules, like procedurally cohe-
sive ones, tend to be composed of partial functi ons whose only relationship to (
module compute table-A-avg and table-B-avg one another is that they all happen to be carried out at a certain time . The
(
activities are usually more closely related to activities in other modules than
uses table-A, table-B
they are to one another, a situation that leads to tight coupling. (
returns table-A-avg, table-Bvavg In Figure 6.10, the module INITIALIZE initializes many different func-
table-A-total : = 0 tions in a might y sweep, causing it to be broadly related to several other mod-
table-B-total : = 0 ules in the system-a condition that is reflected by broad coupling to its (
for i = i to 100 caller. A temporally cohesive module also has some of the same difficulties as
a procedurally cohesive one . The programmer is tempted to share code among (
add table-A (i) to table-A-total
activities related only by time , and the module is difficult to reuse, either in this
add table-B (i) to table-B-total
system or in others.'
endfar For instance, if a maintenance change later requires you to put out the cat (
table-A-avg : = table-A-total/l00 in the middle of the afternoon, you'd be obliged to put out the milk bottles,
table-B-avg : = table-B-totaI/100 (
brush your teeth, and turn off the TV, all of which may be highly inconven-
endmodule ient. In Figure 6.10, if you want to re-initialize TAPE B elsewhere in the sys- (
tem , then you're faced with two unfortunate choices. To avoid resetting the
(
Table B ~ bTable-A Avg whole system to zero, you could either introduce flags indicating to INITIAL-
IZE which part(s) of it should be executed, or write another piece of code for (
Table A ~bTable-B Avg
dealing with TAPE B. Both of these solutions degrade maintainability.
(
Procedural and temporal modules are quite similar. They can be created
by taking scissors to a flowchart. The degree of their black boxness, or coloring, (
COMPUTE varies from dark gray to light gray, since it is not very easy to state simply the
TABLEAAVG
AND (
TABLE B AVG 'Clearly, initialization and termination must be done. Chapter 7 discuss es the best way to
Figure 6.9 organize thes e tasks.
(
( ,
(
(
( 92 Cohesion Chap. 6 Sec. 6.6 logical Cohesion 93
(
module initialize module general io routine
( updates a-counter. b-counter, items table, uses input nag r to choose which function '/
totals table. switch-a, switch-b updates record-A
( rewind tape-a define record-B as 80 char I" working '/
set a-counter to 0 define record-C as 120 char r storage 'f
(
rewind tape-b if input nag - I
( set b-counter to 0 tben write record-A to new master file
clear items table read tran fi le1 into record-B
( elseif input nag - 2
clear totals table
set switch-a to off INITIALIZE tben if record-A - all spaces
(
set switch-b to on tben read tran file I into record-B Record-A? J .!. Becord-B
{ endmodule Figure 6.10
endif
(
read Iran file2 into record-C Input
Flag
T 6t Aecord-C
function of such a module without listing its internal details. They are similar elseif input nag - 3
( as well in that the coupling to procedural and temporal modules ranges from tben read Iran file I into record-B
mediocre to poor. The difference between them is like the difference between read master file I into record-C
( read master file2 into record-A GENERAL
sequential and communicational cohes ion . The order of execution of activities endif 10 ROUTINE
( is more important in procedurally cohesive modules. In addition, procedural return record-B. record -C
modules tend to share loops and decisions between functions, whereas tempo- endmodule
( ral modules tend to contain more straight-line code.
Figure 6.11
(
( .6 LOGICAL COHESION The activities in a logically cohesive module fall into roughly the same
category, having some similarities as well as differences. Unfortunately, this
(
A logically cohesive module is one whose elements contribute to activities of leads the programmer into knotting together the code of the activities by allow-
( the same general category in which the activity or activities to be executed are ing activities to share common lines of code . So not only does a logically
selected from outside the module. Keeping this definition in mind , consider cohesive module have an ugly exterior with maybe a dozen different parame-
l the following example. Someone contemplating a journey might compile the ters fighting to use four accesses, but its inside resembles a plate of spaghetti
( following list: mixed with noodles and worms. The resulting module is neither easy to un-
derstand nor to maintain.
( 1. GO BY CAR Try understanding the code for the logically cohesi ve module in Figure
2. GO BY TRAIN 6.11 . [This is an example from real life rewritten to eliminate the original
(
3. GO BY BOAT GOTOs, which made it totally incomprehensible.)
( The example represents not so much the sharing of code as the sharing of
4. GO BY PLANE
buffer space, exploiting such facts as TRAN FILE2 and MASTER FILE1 records
(
are both 120 characters long and are never read together. Notice that
What relates thes e activities? They're all means of transport, of course. But a
( RECORD-A sometimes is read , sometimes is written, and sometimes acts as a
crucial point is that for any journey, a person must choose a specific subset of
flag-a ghastly piece of hybrid coupling.
( these modes of transport. It's un likely anyone would use them all on any
Have you got that? Or would you like some clarification?
particular journey.
( A logically cohesive module contains a number of activities of th e same
/* Clarification of GENERAL 10 ROUTINE:
( general kind. To use the module, we pick out just the piece[s) we need. Thus,
a logically cohesive module is a grab bag of activities. The activities, although
( RECORD-B and TRAN FILE records are 80 chars
different, are forced to share the one and only interface to the module. The
meaning of each parameter depends on which activity is being used; for certain RECORD-C, TRAN FILE2 and MASTER FILE1 records are 120 chars
( RECORD-A, MASTER FILE1 and NEW MASTER FILE records are 142
activities, some of the parameters will even be left blank [although the calling
( module still needs to use them and to know their specific types). chars
(
if
(

94 Cohesion Chap. 6 Sec. 6.7 Coincidental Cohesion 95 (

(
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 . (

Neither Are the


Activit ies
in t he Same
?:.'
Y 6 L 1le I
09 a
6.11 COMPARISON OF LEVELS OF COHESION (
(
General No 7. Coinc idental Table 6.2 presents a summary of the specific qualities of each type of cohe-
CategOry?
sion. (
Figure 6.13 I would like to add a footnote to this section on the comparative virtues of
each level of cohesion, a footnote based on my experiences as a consultant in (
evaluating the worthiness of modules in both commercial and scientific sys- ( ,
6.9 A DECISION TREE FOR MODULE COHESION tems. It turns out that the severity of problems that a module in practice may
cause falls into ranges, one range for each level of cohesion. Where a particular (
Some people prefer to use a decision tree in order to determine the level of module lies within the range for its cohesion depends on a number of factors
cohesion of a module. To use the tree in Figure 6.13, start at the left and [e.g., size and degree of factoring, as discussed in Chapter 7). Figure 6.15 (
proceed toward the right. When you answer a question about the module, shows these ranges for each level of cohesion:
follow the path indicated by your answer. You will eventually arrive at the Figure 6.15 shows the lifetime cost that modules of each type of cohesion
level of cohesion for that module. contribute to overall system maintenance. It indicates that you would not be (
excommunicated from the Structured Designers' Union for creating an occa- (
sional small, clean, well-factored, logically cohesive module. But, if your sys-
6.10 ANDING THE LEVEL OF COHESION tem as a whole were filled with modules of dubious cohesion, then it would (
become obscure, inflexible, and expensive at the system level. If you find
Cohesion is a measure of module strength and acts somewhat like a chain, yourself regularly creating modules of below communicational cohesion, then I (
holding together the activities in the module. If all the activities of a module suggest that you hang up your template and take up a profession less challeng- (
are related by more than one level of cohesion, the module has the strength of ing than Structured Design, lion-taming, for instance.
the strongest level of coh esion. This is the chains-in-parallel rule.' If activities (
with in a module are held together by different levels of cohesion, the module
has the strength only of the weakest. This is the chains-in-series rule." SUMMARY
( .
For example, a module may contain some activities related procedurally, ( \
while other activities may be merely coincidentally related. In this case, the Cohesion is the measure of the functional relatedness of elements (instructions,
module as a whole is only coincidentally cohesive. (
data definitions, etc.) within a single module. In a good design , the cohesion of
every module is high. Together with coupling, cohesion is one of the best
• Think of a chain capable of supporting 20 pound. tied In parallel with a chain capable of
supporting only 10 pounds. The resulting fal chain can hold at least 20 pounds .
measures of the quality of a design.
A module may exhibit any of seven levels of cohesion depending on how
I Think of the 20-pound chain tied in series with the to-pound chain . The resulting long
chain can hold only 10 pounds. the activities within the module are related. In sequence from best to worst, {

\
(
(

(
( 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 (

municational cohesion tends to be significantly higher than that of modules of


the four lowest levels of cohesion.

EXERC ISE

Each of the modules below is accompanied by a short sentence describing its


activities. Detennine as well as you can (without seeing each module on a structure
chart) each module's level of cobesion:
7
AFrINl after input. add control items and verify totals
AFI'IN2 after input . write proof tape, add control items. verify totals
GENREPT produce report either a sales report. a project status report. or a
customer transaction report
Additional
SYNCH
OUTIRAN
check syntactic correctness of space-vehicle guidance parameters
print transaction and copy it to tape
Design Guidelines
UPCREDOur update current credit record and write it to disk (
STARTIT open files, obtain Iirst transaction and first master record. and print
page headings
NEWrRAN update record on Iile and get next transaction (
CIR CDISP from an electrical connection matrix. produce a circuit diagram ( .
Answer
AFI'INI Sequential (if the added control items are the totals being verified) Designin g maintainable systems requires more than the criteria of coupling and
AFI'IN2 We know that AFTINl was sequential, but "write proof tape" is an cohesion. For example. if we relied on coupling alone. we wo u ld always pro-
activity whose strongest relationship to the other two is that it's done duce systems consisting of a single module. And, we could hardly say that the
at the same time (that is. "after input"). Since "write proof tape"
module was tightly coupled to oth er modules since there would be no other
could be done either before or after the other two activities, the
strongest cohesion for the whole module is temporal. This is an modules! Cohesion wouldn't help much either. because the cohesion of that
example of the chains-in-series rule. single module would probably be quite high. Therefore. we need to take other
GENREPT Logical design guidelines into account. This chapter explores 13 such guidelines: fac-
SYNCH Functional toring. decision-splitting. system shape. error reporting. editing, state memory.
matching data structures, informational clusters, initializing and terminating
OUTIRAN Communicational. also temporal. but since these two types of cohe-
sion apply to the module as a whole. the stronger applies. This modules, restrictivity/generality. redundancy. fan-out. and fan-in .
provides an example of the chains-in-parallel rule.
UPCREDOur Sequential 7.1 FACTORING
STARTIT Temporal (not coincidental, because the activities are all done at one
time) Factoring is the separation of a function contained as code in one module into a (
NEWrRAN Procedural new module of its own. It may be done for any of the following six reasons :
CIRCDISP Functional (a complicated function high in the structure chart. no
doubt, but a single problem-related function nonetheless] 1. to reduce module size;
2. to get the modular advantages of classic top-down design. thus making the
system easier to understand and making modifications to the system more
loca lized and straightforward;
3. to avoid having the sarne function carried out by more than one module;
103

You might also like