Chapter 22 of 32

Modularity, Coupling & Cohesion

In Software Design Principles we said a good design splits a system into modules, and that each module should be functionally independent. That raises two practical questions: how should we split, and how do we know whether a split is good?

This chapter answers both. We define modularity, then study the two classic yardsticks introduced by Larry Constantine and Edward Yourdon in Structured Design: coupling (between modules) and cohesion (inside a module). These two words appear in nearly every university exam paper and in many design interviews.

Goal of modular design: high cohesion and low coupling. Each module should do one well-defined job, and depend on other modules as little as possible.


What Is Modularity?

Modularity is the degree to which a system is divided into separately named and addressable components (modules), each of which can be designed, understood, built, tested and changed with limited knowledge of the others.

A module can be a function, a class, a package, a library or even a microservice, depending on the level you are looking at. What matters is that it has a clear interface (what others may use) and an implementation (what others need not know).

Why split at all? The divide-and-conquer argument

Let C(P) be the perceived complexity of problem P, and E(P) the effort to solve it. Experience suggests:

If  C(P1) > C(P2)      then  E(P1) > E(P2)          (harder problems take more effort)

and C(P1 + P2) > C(P1) + C(P2)                       (a combined problem is harder
                                                     than its parts solved separately)

therefore  E(P1 + P2) > E(P1) + E(P2)

Because the parts interact, the whole is more than the sum of the parts. Splitting a problem along sensible lines reduces total effort. This is the textbook justification (Pressman) for modularity.

Can we split forever?

No. Every extra module adds an interface: parameters to pass, calls to make, documents to keep in sync. So:

  • Cost per module falls as the number of modules grows (each module is smaller).

  • Cost of integration rises as the number of modules grows (more interfaces).

number of modules :  few  ..........  M  ..........  many
cost per module   :  high     ↘     medium     ↘     low
integration cost  :  low      ↗     medium     ↗     high
total cost        :  high     ↘     MINIMUM    ↗     high

There is a "region of minimum cost" around some number M of modules. We cannot compute M exactly, but the lesson is clear: under-modularity and over-modularity are both bad.

Meyer's criteria for a good modular method

Bertrand Meyer gave five criteria that a design method should satisfy:

CriterionMeaning
DecomposabilityIt helps break a big problem into smaller sub-problems.
ComposabilityExisting modules can be combined to build new systems (reuse).
UnderstandabilityA module can be understood on its own, without reading all the others.
ContinuityA small change in requirements causes changes in only a few modules.
ProtectionAn error inside one module stays inside it (or nearby) and does not spread.

Coupling

Coupling is a measure of the degree of interdependence between two modules. Low (loose) coupling is good; high (tight) coupling is bad.

Why is high coupling bad? If module A depends on many internal details of module B, then:

  • A change in B forces changes in A (ripple effect).

  • You cannot understand A without understanding B.

  • You cannot test or reuse A without dragging B along.

  • A bug in B shows up as strange behaviour in A.

Types of coupling (best to worst)

#TypeModules share…Example
0No couplingNothing; they never interactA logging utility and a PDF font loader
1Data coupling (best real case)Only elementary data passed as parameterscomputeInterest(principal, rate, years)
2Stamp couplingA whole data structure, of which the callee uses only partPassing the whole Student record to a function that needs only the roll number
3Control couplingA flag/parameter that controls the callee's internal logicreport(marks, mode) where mode picks average, max or min
4External couplingAn externally imposed format, protocol or device interfaceTwo modules that both depend on a specific bank's file format
5Common couplingGlobal dataSeveral functions reading and writing a global currentUser variable
6Content coupling (worst)One module directly uses or modifies another's internalsModule A modifies a private variable of B, or jumps into the middle of B's code

A handy memory aid for the order (best → worst): Data, Stamp, Control, External, Common, Content: "Don't Stop Coding, Everyone Can Code".

Why each level is worse than the previous

  • Stamp vs data: the callee now depends on the structure's layout. Add a field to Student and the function may need to be recompiled or retested even though it never used that field. It also receives data it should not see.

  • Control vs stamp: the caller must know how the callee works inside ("mode 2 means max"). The two modules share knowledge of logic, not just data.

  • Common vs external/control: any module can change the global at any time, so a bug can come from anywhere. You cannot tell who depends on it without searching the whole program.

  • Content: there is no interface at all. Any internal change in B can break A.

Seeing control coupling in code

# Control coupling: caller passes a flag that steers the callee's logic
def report(marks, mode):
    if mode == 1:
        return sum(marks) / len(marks)
    elif mode == 2:
        return max(marks)
    else:
        return min(marks)

# Data coupling: each function gets only the data it needs
def average(marks): return sum(marks) / len(marks)
def highest(marks): return max(marks)
def lowest(marks):  return min(marks)

m = [72, 88, 65, 91]
print(report(m, 1), report(m, 2), report(m, 3))
print(average(m), highest(m), lowest(m))

Output:

79.0 91 65
79.0 91 65

Both versions give the same answers, so why care? With report, every caller must remember what 1, 2 and 3 mean, and adding "median" means editing a function that others already rely on. The second version has three small, data-coupled functions with self-explaining names. Notice also that report has logical cohesion (see below): control coupling and weak cohesion often appear together.

How to reduce coupling

  • Pass only the data that is needed (move from stamp to data coupling).

  • Replace flags with separate functions or with polymorphism (Strategy pattern).

  • Avoid global variables; pass values explicitly or wrap shared state in one module with a clear interface.

  • Keep fields private and expose methods (information hiding).

  • Isolate external formats behind an adapter module, so only one module knows the bank's file format.

  • Depend on interfaces, not concrete classes (Dependency Inversion, from Software Design Principles).


Cohesion

Cohesion is a measure of how strongly the elements inside a single module belong together, that is, how focused the module is on one task. High cohesion is good; low cohesion is bad.

A highly cohesive module "does one thing". You can describe it in a short sentence without "and" or "or". If your description needs "and", the module may be doing two jobs; if it needs "or", it may be doing one of several unrelated jobs.

Types of cohesion (worst to best)

#TypeElements are grouped because…Example
1Coincidental (worst)No meaningful reason; chanceA Utils module with printBanner(), calcGST() and resizeImage()
2LogicalThey do logically similar things; one is chosen by a flagAn inputAll(type) routine that reads from keyboard, file or network depending on type
3TemporalThey happen at the same timestartup() that opens the log, clears counters, loads config and shows the splash screen
4ProceduralThey follow a fixed order of execution, but work on different data"Check login, then load menu, then show today's notice"
5CommunicationalThey operate on the same dataGiven a roll number: fetch the student's name and fetch the student's attendance
6SequentialOutput of one element is input to the nextRead marks → compute percentage → compute grade
7Functional (best)All elements contribute to a single well-defined taskcomputeSquareRoot(x), validatePAN(pan)

Memory aid (worst → best): Coincidental, Logical, Temporal, Procedural, Communicational, Sequential, Functional: "Can Lazy Teachers Pass Class Students Freely?"

Telling the middle levels apart

Procedural, communicational and sequential are the ones students confuse. Ask these questions in order:

Does one step's OUTPUT feed the next step's INPUT?          → Sequential
Else, do all steps work on the SAME input data?             → Communicational
Else, are the steps just done in a fixed ORDER?             → Procedural
Else, are they grouped only because they run at same TIME?  → Temporal
Else, is one of several similar actions picked by a FLAG?   → Logical
Else                                                        → Coincidental

And if the whole module is one single job with nothing extra, it is functional.


Coupling vs Cohesion

AspectCouplingCohesion
MeasuresDependence between modulesRelatedness within a module
Desired levelLow (loose)High (strong)
Concept ofInter-moduleIntra-module
Best typeData couplingFunctional cohesion
Worst typeContent couplingCoincidental cohesion
Effect of a bad valueRipple effects, hard reuseHard to understand, name and change

The two are related. If you put things that belong together into the same module (high cohesion), they no longer need to talk across module boundaries, so coupling falls. If you scatter related things across modules (low cohesion), those modules have to share data constantly, so coupling rises.


Fan-in and Fan-out

On a structure chart (a tree of which module calls which), two simple counts help judge a design:

  • Fan-out of a module = the number of modules it directly calls. Very high fan-out means the module controls too much; consider adding an intermediate layer.

  • Fan-in of a module = the number of modules that directly call it. High fan-in is usually good for low-level utility modules: it means they are reused.

                 [ GenerateResults ]
                /         |          \
       [ReadMarks]  [ComputeGrade]  [PrintCard]
             \            |            /
              \           |           /
               [ ValidateRollNumber ]

Fan-out(GenerateResults)    = 3
Fan-in(ValidateRollNumber)  = 3

A common guideline is "high fan-in, low to moderate fan-out", with the overall structure looking like a well-balanced tree.


Worked Exam Example

Classify each module.

  1. initialise(): opens the database connection, sets the language to English and clears the shopping cart.

  2. processPayment(): reads the card number, validates it, then charges the validated card.

  3. studentInfo(roll): returns both the address and the fee balance for a roll number.

  4. misc(): contains a date formatter, a factorial function and a colour picker.

  5. Module X passes a Customer object to module Y; Y only reads customer.email.

  6. Module X sets a global taxRate that modules Y and Z read.

Answers.

  1. Temporal cohesion: unrelated actions grouped because they happen at start-up.

  2. Sequential cohesion: the output of each step (card number, validated card) is the input to the next.

  3. Communicational cohesion: both tasks use the same input (roll number) but neither feeds the other.

  4. Coincidental cohesion: no relationship at all.

  5. Stamp coupling: a whole structure is passed, but only one field is used. Passing just the email would make it data coupling.

  6. Common coupling: modules communicate through global data.


Common Mistakes

  • Reversing the orders. Coupling is usually listed best → worst (data first), cohesion worst → best (coincidental first). Read the question carefully to see which direction it asks for.

  • Calling stamp coupling "bad". It is only one step worse than data coupling and is often acceptable, especially in object-oriented code where passing objects is natural.

  • Confusing logical and coincidental cohesion. Logical cohesion has a theme (all are "input" routines) and a selector flag; coincidental has no theme.

  • Thinking zero coupling is the aim. Modules must cooperate; the aim is the weakest necessary coupling, which is usually data coupling.

  • Making a module "functional" by giving it a vague name. handleEverything() is one name but not one job.


Interview and Exam Questions

Q1. Arrange in increasing order of desirability: common, data, control, content, stamp coupling.

Least to most desirable: content < common < control < stamp < data.

Q2. Which is the best and which is the worst type of cohesion?

Best: functional. Worst: coincidental.

Q3. Why does using global variables increase coupling?

Every module that reads or writes the global becomes dependent on every other module that does so (common coupling). A change in how one module uses it can break the others, and you cannot find all dependents without searching the whole code base.

Q4. A function receives a boolean "isAdmin" that makes it skip half its code. What coupling is this, and how would you fix it?

Control coupling: the caller controls the callee's internal logic. Fix it by splitting into two functions (or two classes behind a common interface) and letting the caller pick the right one.

Q5. How are coupling and cohesion related?

They tend to move in opposite directions. Grouping related elements in one module raises cohesion and reduces the need for inter-module communication, which lowers coupling.

Q6. Is high fan-in good or bad?

Generally good for low-level modules, because it indicates reuse. Very high fan-out, on the other hand, suggests a module is coordinating too much.


Summary

  • Modularity divides a system into separately addressable modules. Too few or too many modules both raise total cost.

  • Coupling (between modules) should be low. Best → worst: data, stamp, control, external, common, content.

  • Cohesion (within a module) should be high. Worst → best: coincidental, logical, temporal, procedural, communicational, sequential, functional.

  • High cohesion and low coupling support each other and give understandable, testable, reusable, maintainable modules.

  • Use fan-in/fan-out on a structure chart as a quick sanity check.

  • Next, UML Diagrams shows the standard notation for drawing object-oriented designs.