liveBook · Manning

Cohesion

As explained in Simple Object-Oriented Design: Create clean, maintainable applications

Cohesion is the degree to which a software unit's responsibilities and elements belong together and support a focused purpose.

Cohesion measures whether a software unit’s responsibilities belong together and support one clear purpose. A cohesive class or method does one thing, making the code easier to understand, test, and maintain. section 2.1

Small units make testing a design choice: developers can exercise one piece of business logic in isolation or test several pieces together. When behavior remains in one large unit, that choice disappears. section 2.1

Use cohesion as a practical guide while code evolves:

  • Build complex behavior from smaller methods or classes, each with a focused responsibility. section 2.1
  • Move new complexity to a separate location instead of continually extending an existing class. section 2.3
  • Move complex business rules into their own class and break large business flows into multiple steps. section 2.3
  • Treat small units as a straightforward starting rule, then refactor when a class or method proves insufficiently cohesive. section 2.3.2

A growing business flow

When a class accumulates business rules and an increasingly long workflow, separate the rules into their own class and divide the flow into smaller steps. For highly complex workflows, domain events or an event-based system may fit; otherwise, prefer simpler mechanisms. section 2.3 section 2.3.2

Figure 2.1 Smaller units are always better than large units.

Use the figure to compare large units with smaller, focused units. section 2.1

How Simple Object-Oriented Design: Create clean, maintainable applications covers it

How deep it goes
Defines single responsibility, explains testing and maintenance benefits, and gives refactoring heuristics while deferring event-system implementation details.
Examples
Uses smaller classes and methods, separated business-rule classes, decomposed workflows, and a comparison figure.
What you can do after
Diagnose overgrown units and refactor responsibilities, business rules, and workflows into smaller, more testable parts.
How it connects
Connects cohesion to the Single Responsibility Principle, business rules, domain events, event-based systems, and microservices.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Simple Object-Oriented Design: Create clean, maintainable applications. The section links point to the parts of the book it draws on.