High Cohesion and Low Coupling

Back to Index

Introduction

High cohesion and low coupling are essential principles in software design. They aim to create systems that are easy to understand, maintain, and extend. These principles emphasize the organization of components within a system:

Benefits

Examples

High Cohesion

Consider a class that manages both user authentication and email notifications:

class UserManager {
    void authenticateUser(String username, String password) {
        // Authentication logic
    }

    void sendWelcomeEmail(String email) {
        // Email sending logic
    }
}
            

This class violates high cohesion because it handles two different responsibilities. To improve cohesion, split the responsibilities into separate classes:

class Authenticator {
    void authenticateUser(String username, String password) {
        // Authentication logic
    }
}

class EmailNotifier {
    void sendWelcomeEmail(String email) {
        // Email sending logic
    }
}
            

Low Coupling

Consider two classes that are tightly coupled:

class OrderProcessor {
    private PaymentProcessor paymentProcessor = new PaymentProcessor();

    void processOrder(Order order) {
        paymentProcessor.processPayment(order.getTotal());
    }
}
            

This creates a strong dependency between OrderProcessor and PaymentProcessor. To reduce coupling, use dependency injection:

class OrderProcessor {
    private PaymentProcessor paymentProcessor;

    OrderProcessor(PaymentProcessor paymentProcessor) {
        this.paymentProcessor = paymentProcessor;
    }

    void processOrder(Order order) {
        paymentProcessor.processPayment(order.getTotal());
    }
}
            

Takeaway

By striving for high cohesion and low coupling, you create systems that are modular, easier to understand, and more resilient to changes. These principles are the foundation of good software design.

Back to Index