OCP-open-closed-principle

img

Open/Closed Principle (OCP)

The Open/Closed Principle (OCP) is one of the five SOLID principles of object-oriented design. It states that software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. This means that the behavior of a module can be extended without modifying its source code, enhancing flexibility and reducing the risk of introducing bugs.

Key Benefits:

  1. Maintainability: By avoiding modifications to existing code, the risk of introducing new bugs is minimized.
  2. Scalability: New functionality can be added with minimal impact on the existing system.
  3. Flexibility: Encourages the use of abstractions, making the codebase more adaptable to changing requirements.

Example:

Consider a class DiscountCalculator that calculates discounts for different customer types.

Violation of OCP:

public class DiscountCalculator {
    public double calculateDiscount(String customerType, double amount) {
        switch (customerType) {
            case "Regular":
                return amount * 0.05;
            case "Premium":
                return amount * 0.10;
            default:
                return 0;
        }
    }
}

To add a new discount type, you must modify the calculateDiscount method, violating OCP.

Adhering to OCP (Using Strategy (Design Pattern) design pattern):

// Step 1: Define an abstract base class
public abstract class DiscountStrategy {
    public abstract double calculateDiscount(double amount);
}

// Step 2: Implement specific discount strategies
public class RegularDiscount extends DiscountStrategy {
    @Override
    public double calculateDiscount(double amount) {
        return amount * 0.05;
    }
}

public class PremiumDiscount extends DiscountStrategy {
    @Override
    public double calculateDiscount(double amount) {
        return amount * 0.10;
    }
}

// Step 3: Use the strategy in DiscountCalculator
public class DiscountCalculator {
    public double calculateDiscount(DiscountStrategy strategy, double amount) {
        return strategy.calculateDiscount(amount);
    }
}

In the second example, the DiscountCalculator class does not need to be modified to add a new discount type. Instead, new discount strategies can be created by extending the DiscountStrategy class. This adheres to the OCP, making the system more maintainable and scalable.


Backlinks