Cohesion in Java with Example

Introduction

Cohesion is a measure of how closely related and focused the responsibilities of a single module or class are. In Object-Oriented Programming (OOP), a highly cohesive class is one that performs a single task or a group of related tasks, making the class easier to maintain and understand. High cohesion often correlates with low coupling, leading to a more modular and maintainable codebase.

Table of Contents

  1. What is Cohesion?
  2. Benefits of High Cohesion
  3. Types of Cohesion
  4. Example: Low Cohesion vs High Cohesion
  5. Real-World Examples of Cohesion
  6. Conclusion

1. What is Cohesion?

Cohesion refers to the degree to which the elements inside a module or class belong together. It describes how well the methods and properties of a class are related to each other. High cohesion means that a class is responsible for only one thing or a group of related things, while low cohesion means that a class has many unrelated responsibilities.

2. Benefits of High Cohesion

  • Improved Maintainability: High cohesion makes classes easier to maintain and update because each class has a clear and focused responsibility.
  • Enhanced Readability: Classes with high cohesion are easier to understand and reason about.
  • Increased Reusability: Highly cohesive classes are more likely to be reused in different parts of an application or in different projects.
  • Simplified Testing: Testing is easier for highly cohesive classes since they perform a single task or a group of related tasks.

3. Types of Cohesion

  1. Low cohesion
  2. High Cohesion

4. Example: Low Cohesion vs High Cohesion

Example of Low Cohesion

In a class with low cohesion, responsibilities are scattered and unrelated, making the class difficult to maintain and understand.

public class LowCohesionClass {
    // Unrelated methods grouped together

    public void calculateSalary() {
        // Calculate employee salary
    }

    public void printReport() {
        // Print employee report
    }

    public void sendEmail() {
        // Send email to employee
    }
}

Example of High Cohesion

In a class with high cohesion, responsibilities are related and focused, making the class easier to maintain and understand.

Employee Class

public class Employee {
    private String name;
    private double salary;

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}

SalaryCalculator Class

public class SalaryCalculator {
    public double calculateAnnualSalary(Employee employee) {
        return employee.getSalary() * 12;
    }
}

ReportPrinter Class

public class ReportPrinter {
    public void printEmployeeReport(Employee employee) {
        System.out.println("Employee Report: " + employee.getName() + ", Salary: " + employee.getSalary());
    }
}

EmailService Class

public class EmailService {
    public void sendEmail(String email, String message) {
        System.out.println("Sending email to: " + email + ", Message: " + message);
    }
}

Explanation

  • LowCohesionClass: Contains methods that perform unrelated tasks such as calculating salary, printing reports, and sending emails. This makes the class difficult to understand and maintain.
  • High Cohesion Example: Responsibilities are divided into separate classes: Employee, SalaryCalculator, ReportPrinter, and EmailService. Each class has a single responsibility, making the code more modular and easier to maintain.

5. Real-World Examples of Cohesion

Example 1: Library System

In a library system, you can have classes like Book, LibraryMember, LibraryCatalog, and LoanService. Each class has a specific responsibility, such as managing book details, handling member information, maintaining the catalog, and managing book loans, respectively.

Book Class

public class Book {
    private String title;
    private String author;
    private String isbn;

    // Constructors, getters, and setters
}

LibraryMember Class

public class LibraryMember {
    private String memberId;
    private String name;

    // Constructors, getters, and setters
}

LibraryCatalog Class

public class LibraryCatalog {
    private List<Book> books;

    public void addBook(Book book) {
        books.add(book);
    }

    public Book findBookByIsbn(String isbn) {
        for (Book book : books) {
            if (book.getIsbn().equals(isbn)) {
                return book;
            }
        }
        return null;
    }
}

LoanService Class

public class LoanService {
    public void loanBook(LibraryMember member, Book book) {
        // Logic to loan a book to a member
    }
}

Example 2: E-commerce System

In an e-commerce system, you can have classes like Product, ShoppingCart, Order, and PaymentProcessor. Each class is responsible for a specific part of the system.

Product Class

public class Product {
    private String name;
    private double price;

    // Constructors, getters, and setters
}

ShoppingCart Class

public class ShoppingCart {
    private List<Product> products;

    public void addProduct(Product product) {
        products.add(product);
    }

    public double calculateTotal() {
        double total = 0;
        for (Product product : products) {
            total += product.getPrice();
        }
        return total;
    }
}

Order Class

public class Order {
    private List<Product> products;

    // Constructors, getters, and setters
}

PaymentProcessor Class

public class PaymentProcessor {
    public void processPayment(Order order, String paymentDetails) {
        // Logic to process payment
    }
}

6. Conclusion

Cohesion is a critical concept in software design that affects the maintainability, readability, and reusability of a system. High cohesion within classes leads to a more modular and understandable codebase, making it easier to manage and extend. By focusing on creating highly cohesive classes, developers can build robust and scalable software systems.

Happy coding!

Comments

Post a Comment

Leave Comment