liveBook · Manning

Cohesion

As explained in Grokking Software Architecture

Cohesion is the degree to which the responsibilities within a software component belong together.

Cohesion is how well the responsibilities inside a software component belong together. Think of a well-written paragraph: every sentence contributes to one clear idea. A class devoted to calculating shipping costs is similarly focused. A class that mixes authentication, logging, and currency formatting is more like a paragraph that jumps from cooking to car repair to the weather. section 3.3

Cohesion looks inside a module; coupling looks at dependencies between modules. Together, they help assess separation of concerns. The goal is focused components that connect without depending on each other's internal details. This thinking applies from methods and classes up to components and entire systems. section 3.3 section 3.7

Keep related behavior with its data

An Order object that only holds data while its calculation and validation behavior is scattered elsewhere lacks cohesion. It also cannot protect its own state: another class could set its total to a negative value. Keeping related behavior with the data helps make the object's responsibility clear. section 4.7.2

More focused classes can make changes easier to locate and pieces easier to test independently. The tradeoff may be more files to manage: separating payment, validation, and notification work adds structure, but avoids leaving those jobs tangled together. section 3.5.4

Try a quick cohesion audit:

  • Pick a method or class over 50 lines long, or one that feels complicated and intimidating. section 3.9
  • Add a comment describing what each block does, then read only the comments. Do they tell one focused story or describe several unrelated jobs? section 3.9
  • Optionally ask an AI assistant to identify responsibilities as a second set of eyes. Use your own judgment to assess its suggestions. section 3.9

How Grokking Software Architecture covers it

How deep it goes
Defines high and low cohesion through analogies and contrasting classes, then provides a comment-driven audit.
Examples
Contrasts a shipping-cost class with a class mixing authentication, logging, and currency formatting, and examines an anemic Order object.
What you can do after
Practice performing a comment-driven structural audit to spot unrelated responsibilities in a method or class.
How it connects
Connects cohesion with separation of concerns, coupling, and the single responsibility principle.

Also explained in

Compare how 7 books explain cohesion →

Related concepts

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