The Open/Closed Principle (OCP) states that a class should be open for extension but closed for modification, allowing new functionality without changing existing code.


Problem

Consider a class calculating discounts:

public class DiscountCalculator {
    public double calculateDiscount(double price, String customerType) {
        if (customerType.equals("STANDARD")) {
            return price * 0.05;
        } else if (customerType.equals("VIP")) {
            return price * 0.10;
        }
        return 0;
    }
}

Adding a new discount type means modifying the class, risking bugs.


OCP Solution

Introduce an abstraction:

public interface DiscountStrategy {
    double calculateDiscount(double price);
}

public class StandardDiscount implements DiscountStrategy {
    public double calculateDiscount(double price) {
        return price * 0.10;
    }
}

public class VIPDiscount implements DiscountStrategy {
    public double calculateDiscount(double price) {
        return price * 0.19;
    }
}

Use a context class:

public class DiscountCalculator {
    private DiscountStrategy discountStrategy;

    public DiscountCalculator(DiscountStrategy discountStrategy) {
        this.discountStrategy = discountStrategy;
    }

    public double calculateDiscount(double price) {
        return discountStrategy.calculateDiscount(price);
    }
}

To add a new discount, implement DiscountStrategy without altering existing code.


Benefits

This approach ensures maintainable, extensible, and stable code.

Hinterlasse einen Kommentar

I’m Iman

Mein Name ist Iman Dabbaghi. Ich arbeite als Senior Software Engineer in der Schweiz. Außerdem interessiere ich mich sehr für gewaltfreie Kommunikation, Bachata-Tanz und Musik sowie fürs die Persönlichkeitsentwicklung.

Ich habe einen Masterabschluss in Informatik von der Universität Freiburg in Deutschland, bin Spring/Java Certified Professional (OCP), Certified Professional for Software Architecture (CPSA-F) und ein lebenslanger Lernender 🎓.

EN:

My name is Iman Dabbaghi. I work as a Senior Software Engineer in Switzerland. I am also very interessted in nonviolent communication, Bachata dance and music and also for personal development.

I hold a masters degree in computer science from the university of Freiburg in Germany, am a Spring / Java Certified Professional (OCP), Certified Software Architecture (CPSA-F) and Life Long Learner🎓

Let’s connect