Cohesion is one of the two measures of module boundary quality, alongside coupling: it assesses the order within a module; coupling, the ties between modules. The higher the cohesion and the lower the coupling, the easier it is to change the system: related changes land in one place instead of spreading across the whole codebase.
How cohesion is assessed
Cohesion is a qualitative measure: the code is inspected and assigned to one of the levels. Structured design produced a scale from worst to best; the lower levels signal that a module gathers unrelated responsibilities and should be split.
| Level | What binds the parts | Example |
|---|---|---|
| Coincidental | nothing: the code happened to end up in one place | a util.py file with a list of strings and a tax calculation |
| Logical | operations of the same kind, chosen by a flag | a process(data, mode) function branching over five scenarios |
| Temporal | the moment of execution | an init module mixing network and database settings |
| Procedural | the flow of a single algorithm | the steps of one scenario, assembled without a shared purpose |
| Communicational | shared data | functions that read and write the same record |
| Sequential | the output of one part is the input of another | a parser whose result goes straight into a validator |
| Functional | a single task | an insurance premium calculation module |
Cohesion and coupling
The two dimensions work as a pair: a module with high cohesion is usually easy to separate from its neighbours, while low cohesion almost always brings coupling with it — changing one function requires changing five more. The rule of thumb: split the code by reasons for change, so that similar changes land in the same module.
# low cohesion: one class serves three different reasons for changeclass InvoiceProcessor: def calculate_total(self): ... def render_pdf(self): ... def send_email(self): ... # higher cohesion: each module has a single responsibilityclass InvoiceCalculator: ...class InvoiceRenderer: ...class InvoiceNotifier: ...Where the term comes from
Cohesion and coupling appeared together in early work on structured design: both notions were introduced by Larry Constantine and developed by Tom DeMarco and Meilir Page-Jones; the term has remained in use ever since.
How it is improved
- split the module by reasons for change: keep together what changes for the same reasons, and separate what changes for different ones;
- move unrelated helper functions out of shared util modules to those who use them;
- hide the module’s internals behind an explicit interface, so that its cohesion is not broken from outside.
Robert Martin calls the rule “keep together what changes for the same reasons, and separate what changes for different ones” another definition of cohesion and coupling: the former grows within a module, the latter falls between modules.
Sources
the term is written from these pagesVerified 8 Nov