OOP and design · Topic 9 of 12
Open/closed
Definition​
The open/closed principle says code should be open for extension but closed for modification. You add new behaviour by adding new classes, not by editing code that already works.
Example code​
Adding a new discount without touching the checkout
interface Discount {
int apply(int price);
}
class NoDiscount implements Discount {
public int apply(int price) { return price; }
}
class FestivalDiscount implements Discount {
public int apply(int price) { return price * 90 / 100; }
}
class StudentDiscount implements Discount { // new rule: only a new class was added
public int apply(int price) { return price * 80 / 100; }
}
class Checkout {
int total(int price, Discount discount) { return discount.apply(price); } // never needs to change
}
class Demo {
public static void main(String[] args) {
Checkout checkout = new Checkout();
System.out.println(checkout.total(1_000, new NoDiscount()));
System.out.println(checkout.total(1_000, new FestivalDiscount()));
System.out.println(checkout.total(1_000, new StudentDiscount()));
}
}
// Output:
// 1000
// 900
// 800
Finished this page? Track your progress (saved only in your browser).