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
Ideal
Follows the guideline.
God Object
Anti-pattern where a single object does all the work.
Poor Boundaries
Boundaries between components is poorly selected.
Destructive Coupling
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.