liveBook · Manning

Cohesion

As explained in The Coder Cafe

Cohesion is a software design property describing how strongly the elements within an aggregate belong together and serve a common purpose.

Cohesion measures how strongly the parts of an aggregate belong together. An aggregate might be a module containing classes, a class containing methods, or a function containing instructions. High cohesion means those parts work toward a common purpose. For a class, its methods and constants should focus on one responsibility. section 4.8

A room with a purpose

A bedroom containing a bed, a cutlery cupboard, and shampoo has low cohesion: its contents serve unrelated purposes. Replace the cupboard and shampoo with a wardrobe and an alarm clock, and the contents support resting and getting ready in the morning. The same question helps when assessing a class: do its parts serve one clear task? section 4.8

High cohesion has practical benefits:

  • Readability: a clear purpose makes an aggregate easier to understand. section 4.8
  • Maintainability: a focused aggregate makes the place to change easier to find. section 4.8
  • Testability and reusability: focused behavior is simpler to test and easier to reuse. section 4.8

Watch for shotgun surgery, where one behavior change generally requires edits across several aggregates, or a god object with too many responsibilities. Cohesion also relates to coupling: a focused component often needs fewer interactions with other modules, but high cohesion does not guarantee low coupling. section 4.8 section 4.9

How The Coder Cafe covers it

How deep it goes
Defines cohesion, illustrates high and low cohesion, and identifies benefits and code smells.
Examples
Contrasts bedroom contents serving unrelated purposes with contents supporting rest and morning preparation.
What it assumes
Defines aggregate before applying cohesion to modules, classes, and functions.
What you can do after
Evaluate/understand it by checking whether an aggregate's parts share a purpose and recognizing signs of scattered responsibility.
How it connects
Links cohesion to coupling, single responsibility, shotgun surgery, and god objects.

Also explained in

Compare how 7 books explain cohesion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Coder Cafe. The section links point to the parts of the book it draws on.