All Articles

Cohesion

What is it?

The degree to which parts of a system that will need to change for the same reasons are grouped together. Along with coupling, cohesion is a key factor in the stability and maintainability of a system. Highly cohesive systems with low coupling are the most stable.

High cohesion is an important quality in stable, maintainable systems. Systems can be cohesive at the code, module and service level. High cohesion and low coupling in the modules of a modular monolith or services in microservices are essential.

Business actor cohesion

Cohesion is closely related to the single responsibility principle (SRP). The principle states that code should have only one reason to change. By “reason to change” it means change should be driven by only one discreet business group or actor. Naturally this requires separating code that has different business actors. Because system changes are driven by business actors, the more the SRP is applied the more cohesive the system becomes.

Types of cohesion

A system can display cohesion around different factors. These factors sit on a scale from coincidental cohesion at the worst through to functional cohesion at the best. Functional cohesion groups code around business domain and functionality.

The decomposition techniques in Domain Driven Design can be used to decompose a system into cohesive bounded contexts based on the business domain. The boundaries of these contexts make good module and service boundaries.

Why is it important?

A highly cohesive system reduces the scope of any new change requests. This important for maintainability and stability. The fewer parts of a system that need to change in order to implement a request the cheaper and easier that change is to make. The risk associated with a change goes up with the number of parts of that system you need to change at once.

Cohesion is particularly important when applied to a microservices architecture because cross service changes are particularly expensive and risky to make.