🏡 Back Home

Cohesion and Coupling

Tags:
Links: Single Responsibility Principle


Cohesion

Cohesion is the degree of how a Software Component (class, module, function) is related.

Classes

A class that has a set of variables that is shared among all methods would be maximally cohesive. However, this is not necessarely desired. The more cohesive are the methods and variables the more co-dependent they are. [1]

Coupling

Coupling is about the degree of connection from a software component to other components. When components are mostly independent we say that they are loosely-coupled.

High Cohesion and Low Coupling

A often recommended heuristic that suggests keeping parts of a code base that are related in a single place (high cohesion) and also separating unrelated components as much as possible [2].

Types of Code

Pasted image 20220502191217.png|400

Ideal

Pasted image 20220502191453.png|400
Follows the guideline.

God Object

Pasted image 20220502191556.png|400
Anti-pattern where a single object does all the work.

Poor Boundaries

Pasted image 20220502191619.png|400
Boundaries between components is poorly selected.

Destructive Coupling

Pasted image 20220502191857.png|400
When code is decoupled so much that is difficult to understand its meaning.

Relation to SRP

The SRP informs that the component should have only one responsibility. While the high cohesion and low coupling points in that direction it doesn't guarantee that we'll have only one [2:1].

Analogy with Clustering

It seems like cohesion would be analogous to intra-cluster distance and coupling to inter-cluster distance. Something that could be measured by the Silhouette Coefficient, for example. However, Cohesion and Coupling are not measurable.


  1. oop - Difference Between Cohesion and Coupling - Stack Overflow ↩︎

  2. Cohesion and Coupling: the difference · Enterprise Craftsmanship ↩︎ ↩︎