Cohesion refers to how closely related and focused the responsibilities of a class or module are.

High Cohesion = Good → Class does one thing well. Low Cohesion = Bad → Class tries to do too many unrelated things.

Example

High Cohesion
class InvoicePrinter {
    void printInvoice(Invoice invoice) { ... }
}
Low Cohesion
class InvoiceUtils {
    void printInvoice() { ... }
    void sendEmail() { ... }
    void saveToDatabase() { ... } // unrelated responsibilities
}

Key Points

  • Promotes single responsibility principle (SRP).
  • Leads to easier maintenance, better readability and modular code.
  • Improves reusability and testability.

Real-World Analogy

A coffee machine that only brews coffee = high cohesion. A coffee machine that also plays music, opens garage door and orders pizza = low cohesion.

Tip

If asked about clean code, class design or SRP, bring up cohesion as a key principle. High cohesion = focused, well-designed code.


Parent: _Design Principles