Skip to main content

Cohesion

Cohesion refers to how closely related and focused the responsibilities of a module/class are. It measures how well the methods inside a class are related to each other.

High Cohesion

A class has a well-defined purpose with related methods.

class ReportPrinter {
void printReport() {
System.out.println("Printing report...");
}
}

class EmailSender {
void sendEmail() {
System.out.println("Sending email...");
}
}

class TaxCalculator {
void calculateTax() {
System.out.println("Calculating tax...");
}
}

Explanation

  • Each class has a single, well-defined responsibility, making the system easier to understand, test, and modify.
  • This approach follows high cohesion and SRP.

Low Cohesion

A class does too many unrelated tasks, making it difficult to maintain.

class Utility {
void printReport() {
System.out.println("Printing report...");
}

void sendEmail() {
System.out.println("Sending email...");
}

void calculateTax() {
System.out.println("Calculating tax...");
}
}

Explanation

  • This class handles printing, emailing, and tax calculations—unrelated responsibilities.
  • If we need to modify one function, the others might be affected.
  • The Single Responsibility Principle (SRP) is violated.