Definition
Cohesion measures how closely related the responsibilities within a single class are.
- High cohesion: all methods and fields serve one clear purpose.
FeeCalculatoronly calculates fees (Single Responsibility Principle). - Low cohesion: the class does many unrelated things. A God class
BankingManagerhandles accounts, trades, notifications, reports, and compliance in one 3000-line class. - Benefits of high cohesion: understandability (one purpose = easy to read), testability (test one thing in isolation), changeability (modify fees without touching notifications), reusability (use FeeCalculator anywhere without dragging unrelated code).
- The AND test: describe the class in one sentence. If you use AND, the class has too many responsibilities.
- Ideal design: high cohesion (focused classes) + loose coupling (interfaces + DI) = clean, maintainable, testable code.
High cohesion: National Bank of India has separate counters: one for deposits, one for loans, one for forex. Each counter does one thing well. Need to change loan processing? Only the loan counter changes. Low cohesion: one clerk handles deposits, loans, forex, complaints, and makes coffee. Overwhelmed, error-prone, and if the clerk is sick, everything stops. That clerk is a God class.
Understanding the Concepts
What is cohesion and why is high cohesion a design goal?
Cohesion is about focus within a single class. High cohesion means every method and field serves one clear purpose.
What does a God class look like (low cohesion)?
// WRONG: God class does everything (3000+ lines, 50+ methods)
public class BankingManager {
public Account createAccount(String name) { /* ... */ }
public void closeAccount(String id) { /* ... */ }
public Trade executeTrade(String symbol, int qty) { /* ... */ }
public void cancelTrade(String tradeId) { /* ... */ }
public void sendSms(String phone, String msg) { /* ... */ }
public void sendEmail(String email, String msg) { /* ... */ }
public Report generateDailyReport() { /* ... */ }
public java.math.BigDecimal calculateBrokerage(java.math.BigDecimal amount) { /* ... */ }
public boolean checkKYC(String customerId) { /* ... */ }
// 5 unrelated areas in one class.
// Changing fee logic might accidentally break notifications.
}
What does high cohesion look like?
// CORRECT: each class does one thing well
public class AccountService {
public Account createAccount(String name) { /* ... */ }
public void closeAccount(String id) { /* ... */ }
}
public class TradeExecutionService {
public Trade executeTrade(String symbol, int qty) { /* ... */ }
public void cancelTrade(String tradeId) { /* ... */ }
}
public class NotificationService {
public void sendSms(String phone, String msg) { /* ... */ }
public void sendEmail(String email, String msg) { /* ... */ }
}
public class FeeCalculator {
public java.math.BigDecimal calculateBrokerage(java.math.BigDecimal amount) { /* ... */ }
}
public class ComplianceService {
public boolean checkKYC(String customerId) { /* ... */ }
}
// Each class: 50-200 lines. Easy to understand. Easy to test. Easy to change.
How do you check if a class has high cohesion?
Use the AND test: describe the class in one sentence.
// LOW cohesion:
// "BankingManager creates accounts AND executes trades AND sends notifications AND calculates fees."
// Multiple ANDs = multiple responsibilities.
// HIGH cohesion:
// "FeeCalculator calculates trading fees."
// One sentence, no AND.
What are the benefits of high cohesion?
| Benefit | Low Cohesion (God Class) | High Cohesion |
|---------|------------------------|---------------|
| Understandability | 3000 lines | 50-200 lines |
| Testability | Loads entire system | Tests one thing |
| Changeability | Fee change risks notifications | Fee change is isolated |
| Reusability | Drag entire God class | Use FeeCalculator alone |
| Merge conflicts | Everyone edits same file | Different files |
What are common mistakes?
The most common mistake is starting with a God class and thinking it is faster because everything is in one place.
What should a senior engineer know?
- The Single Responsibility Principle (SRP) formalizes high cohesion: a class should have only one reason to change.
- In microservices, high cohesion maps to bounded contexts: each service owns one domain.
- SonarQube measures cohesion metrics like LCOM (Lack of Cohesion of Methods) to detect God classes.
Visual Overview
LOW COHESION (God Class) ┌───────────────────────────────┐ │ BankingManager │ │ ┌─────────┐ ┌──────────────┐ │ │ │ Accounts │ │ Trades │ │ │ └─────────┘ └──────────────┘ │ │ ┌─────────┐ ┌──────────────┐ │ │ │ Notify │ │ Reports │ │ │ └─────────┘ └──────────────┘ │ │ ┌─────────┐ │ │ │ Fees │ 3000 lines │ │ └─────────┘ │ └───────────────────────────────┘ HIGH COHESION (Focused Classes) ┌──────────────┐ ┌──────────────┐ │ AccountService│ │ TradeService │ │ 100 lines │ │ 80 lines │ └──────────────┘ └──────────────┘ ┌──────────────┐ ┌──────────────┐ │ NotifyService │ │ FeeCalculator │ │ 60 lines │ │ 50 lines │ └──────────────┘ └──────────────┘
Key Takeaway
Cohesion measures how closely related the responsibilities within a single class are. High cohesion means all methods and fields serve one clear purpose. FeeCalculator only calculates fees. AccountService only manages accounts. Low cohesion means the God class anti-pattern with 3000 lines handling accounts, trades, fees, notifications, and compliance. High cohesion is a design goal because it enables understandability (one purpose = easy to read), testability (test one thing in isolation), changeability (modify fees without touching notifications), and reusability (use FeeCalculator anywhere without dragging unrelated code).
The AND test: describe the class in one sentence. If you use AND, the class has too many responsibilities. BankingManager manages accounts AND executes trades AND calculates fees AND sends notifications: four ANDs = four classes needed. FeeCalculator calculates trading fees: no AND = high cohesion.
Remember one sentence: high cohesion means one class, one purpose, all methods related, and the AND test catches God classes that need to be split.
---