Cohesion
Everyone tells you that you should strive for:
High cohesion, low coupling.
A definition:
Cohesion is about how well elements within a module belong together and serve a common purpose. Coupling is about how much one module depends or interacts with other modules. Thus, cohesion is an intra-module concern whereas coupling cuts across modules [aka inter-module].
(Devopedia)
Cohesion is a property of code that can be measured. It’s like clarity/obscurity, obviousness, or beauty – you need to analyze the code, then you can tell if it’s cohesive, and how. In boxes-and-arrows graphical analysis, it boils down to how many arrows stay inside the group instead of crossing boundaries.
- Example of High Cohesion and Low Coupling with Presenter, View, and View Model: These components can form a logical unit, a module; or you can group them ‘by name’ and destroy cohesion.
Yourdon’s 6 Levels of Cohesion
Levels of cohesion according to Yourdon, pp. 108-132.1
- accidental (coincidental)
- Reducing code duplication for the sake of reducing code duplication results in “coincidental cohesive modules”. See Don't Repeat Yourself.
- The code doesn’t have a shared meaning/intent, only superficial similarity.
- logical
- temporal
- communicational
- sequential
- Reactive code is sequentially cohesive: a sequence of operators, from network request to UI update, can encapsulate the steps even more clearly than a regular, imperative function with multiple lines.
- functional
I call 1–3 “code-level cohesion”; 4–6 is cohesion reflecting the problem space.
When I write “code-level”, this is meant to invoke something similar to “code smell”: it’s purely derived from looking at the code as code, without interpreting its meaning and how it creates higher-level structures or expresses intent.
SMC Cohesion
Yourdon’s 6 levels are built upon the principles behind “SMC Cohesion”. “SMC” stands for Stevens, Myers, and Constantine.2 Constantine is co-author of Yourdon’s book, so it checks out that the following 7 levels found their way from the SMC paper2 into the Yourdon/Constantine book.
- coincidental association
- logical association
- temporal association
- procedural association
- communicational association
- sequential association
- functional association
-
Edward Yourdon and Larry L. Constantine (1979): Structured design, Englewood Cliffs, N.J.: Prentice-Hall. ↩
-
W. P. Stevens, G. J. Myers, and L. L. Constantine (1974): Structured Design, IBM Systems Journal 2, 1974, Vol. 13, S. 115–139. ↩ ↩2