High Cohesion
“How to keep objects focused, understandable, and manageable?” – Craig Larman
Cohesion is a measure of how strongly related and focused the responsibilities of an element are. An element with highly related responsibilities that does not do a huge amount of work has high cohesion.
When to use
Always. Every class should focus on doing one thing well.
Why it matters
- Readability: It’s obvious what the class does.
- Maintainability: You know exactly where to go to fix a bug related to X.
Signs of Violation
- “God Classes” / “Blob Objects” (e.g.,
SystemManagerwith 300 methods). - A class has methods
calculateTax(),renderPage(),connectToWifi(), andsendEmail(). - The class name contains “And” (e.g.,
PageRenderAndDatabaseSaver).
Explanation
Problem
Low cohesion results in classes that are hard to understand, hard to reuse, and hard to maintain. They become dumping grounds for code.
Solution
Break large classes into smaller ones with focused responsibilities (SRP).
Real world analogy
A toolbox. A drawer labeled “Screwdrivers” has high cohesion (it contains only things related to driving screws). A “Junk Drawer” has low cohesion (it contains batteries, gum, receipts, and a hammer). Finding things in the junk drawer is hard.
Pros and Cons
| Pros | Cons |
|---|---|
Comparison
- SRP (Solid): High Cohesion is basically the measure of how well you followed SRP.
- Low Coupling: Usually if you have high cohesion, you likely have lower coupling (because you aren’t grabbing dependencies to do unrelated tasks).
Code example
Typescript
Bad (Violation)
Good (Adherence)
PHP
Bad (Violation)
Good (Adherence)