Add, don't edit
After this: Replace an if per discount with one class per rule, and add a festival rule without editing the checkout.
On this page · 5 sections · 3 checks
A shop has three kinds of discount: none, 10% off, and 150 rupees off. Then the festival season comes, and the shop wants a fourth. In "Interfaces and polymorphism in design" you met code that asks a payment "what are you?" with an if for each kind. Discounts have the same problem, and this lesson names the rule that fixes it.
A function that knows every discount
def price_after(price, kind): if kind == "none": return price elif kind == "percent10": return price - price * 10 // 100 elif kind == "flat150": return max(0, price - 150) else: raise ValueError("unknown discount: " + kind)
print(price_after(1000, "percent10"))print(price_after(1000, "flat150"))try: print(price_after(1000, "festival"))except ValueError as e: print("error:", e)900 850 error: unknown discount: festival
public class Main { static int priceAfter(int price, String kind) { if (kind.equals("none")) { return price; } else if (kind.equals("percent10")) { return price - price * 10 / 100; } else if (kind.equals("flat150")) { return Math.max(0, price - 150); } else { throw new IllegalArgumentException("unknown discount: " + kind); } }
public static void main(String[] args) { System.out.println(priceAfter(1000, "percent10")); System.out.println(priceAfter(1000, "flat150")); try { System.out.println(priceAfter(1000, "festival")); } catch (IllegalArgumentException e) { System.out.println("error: " + e.getMessage()); } }}900 850 error: unknown discount: festival
price_afterpriceAfter has one branch per kind of discount:
"percent10": 1000 − 1000 × 10 ÷ 100 = 900. The division keeps whole rupees: Python's//, and Java's/between twointvalues, drop anything after the point."flat150": 1000 − 150 = 850. The max with 0 stops a price from going below zero."festival"has no branch, so the function raises an error, and the program prints it.
To add the festival discount, you must open this function and add a branch. Every new discount edits code that already works and has already been tested, and every edit is a chance to break one of the old branches.
Open to new kinds, closed to edits
The rule: code should be open to extension but closed to modification. In plain words, you add a new kind by writing new code, without editing the code that is already there. Its name is the , the O of SOLID.
The tool is the one from "Interfaces and polymorphism in design": an interface. Every discount becomes an object with one method, apply, which takes a price and returns the new price.
Press Run it to build the diagram one step at a time.
- classes
- 0
- relations
- 0
from abc import ABC, abstractmethod
class DiscountRule(ABC): @abstractmethod def apply(self, price): pass
class NoDiscount(DiscountRule): def apply(self, price): return price
class PercentOff(DiscountRule): def __init__(self, percent): self.percent = percent
def apply(self, price): return price - price * self.percent // 100
class FlatOff(DiscountRule): def __init__(self, amount): self.amount = amount
def apply(self, price): return max(0, price - self.amount)
class FestivalOff(DiscountRule): def apply(self, price): return price - min(price * 25 // 100, 200)
def checkout(price, rule): return rule.apply(price)
for rule in [NoDiscount(), PercentOff(10), FlatOff(150), FestivalOff()]: print(type(rule).__name__, checkout(1000, rule))print("FestivalOff", checkout(400, FestivalOff()))NoDiscount 1000 PercentOff 900 FlatOff 850 FestivalOff 800 FestivalOff 300
import java.util.List;
interface DiscountRule { int apply(int price);}
class NoDiscount implements DiscountRule { public int apply(int price) { return price; }}
class PercentOff implements DiscountRule { private int percent;
PercentOff(int percent) { this.percent = percent; }
public int apply(int price) { return price - price * percent / 100; }}
class FlatOff implements DiscountRule { private int amount;
FlatOff(int amount) { this.amount = amount; }
public int apply(int price) { return Math.max(0, price - amount); }}
class FestivalOff implements DiscountRule { public int apply(int price) { return price - Math.min(price * 25 / 100, 200); }}
public class Main { static int checkout(int price, DiscountRule rule) { return rule.apply(price); }
public static void main(String[] args) { List<DiscountRule> rules = List.of(new NoDiscount(), new PercentOff(10), new FlatOff(150), new FestivalOff()); for (DiscountRule rule : rules) { System.out.println(rule.getClass().getSimpleName() + " " + checkout(1000, rule)); } System.out.println("FestivalOff " + checkout(400, new FestivalOff())); }}NoDiscount 1000 PercentOff 900 FlatOff 850 FestivalOff 800 FestivalOff 300
Walk through it:
DiscountRuleis the interface. Python writes it as an abstract base class; Java writesinterface.- Each rule is a class that keeps its own number in a field:
PercentOff(10)keeps 10,FlatOff(150)keeps 150. checkoutcallsrule.apply(price). It has noif, and it never asks which rule it was given.- The loop prints each rule's class name and its price for 1000. type(rule).__name__rule.getClass().getSimpleName() gives the name of the object's class.
FestivalOff takes 25% off, but never more than 200:
- On 1000, 25% is 250. That is more than 200, so 200 comes off: 800.
- On 400, 25% is 100, under the limit, so 100 comes off: 300.
The festival rule arrived as one new class. checkout and the three old rules were not touched. That is the principle at work: open to a new rule, closed to edits.
Run it
Write a rule of your own, such as 50 off when the price is at least 500, and add it to the list in the loop. Nothing else needs to change.
Check yourself
The shop wants a new rule: 50 rupees off when the price is at least 500. In the design with DiscountRule, which change follows the open/closed principle?
The festival rule on two prices, then a flat 150 off on a price of 100. What does this print?
from abc import ABC, abstractmethod
class DiscountRule(ABC): @abstractmethod def apply(self, price): pass
class NoDiscount(DiscountRule): def apply(self, price): return price
class PercentOff(DiscountRule): def __init__(self, percent): self.percent = percent
def apply(self, price): return price - price * self.percent // 100
class FlatOff(DiscountRule): def __init__(self, amount): self.amount = amount
def apply(self, price): return max(0, price - self.amount)
class FestivalOff(DiscountRule): def apply(self, price): return price - min(price * 25 // 100, 200)
def checkout(price, rule): return rule.apply(price)
for price in [600, 2000]: print(checkout(price, FestivalOff()))print(checkout(100, FlatOff(150)))import java.util.List;
interface DiscountRule { int apply(int price);}
class NoDiscount implements DiscountRule { public int apply(int price) { return price; }}
class PercentOff implements DiscountRule { private int percent;
PercentOff(int percent) { this.percent = percent; }
public int apply(int price) { return price - price * percent / 100; }}
class FlatOff implements DiscountRule { private int amount;
FlatOff(int amount) { this.amount = amount; }
public int apply(int price) { return Math.max(0, price - amount); }}
class FestivalOff implements DiscountRule { public int apply(int price) { return price - Math.min(price * 25 / 100, 200); }}
public class Main { static int checkout(int price, DiscountRule rule) { return rule.apply(price); }
public static void main(String[] args) { for (int price : List.of(600, 2000)) { System.out.println(checkout(price, new FestivalOff())); } System.out.println(checkout(100, new FlatOff(150))); }}Complete the one line inside FestivalOff's apply: take 25% off the price, but never more than 200. The program should print the same five lines as before.
from abc import ABC, abstractmethod
class DiscountRule(ABC): @abstractmethod def apply(self, price): pass
class NoDiscount(DiscountRule): def apply(self, price): return price
class PercentOff(DiscountRule): def __init__(self, percent): self.percent = percent
def apply(self, price): return price - price * self.percent // 100
class FlatOff(DiscountRule): def __init__(self, amount): self.amount = amount
def apply(self, price): return max(0, price - self.amount)
class FestivalOff(DiscountRule): def apply(self, price): ________ # ← 25% off, but never more than 200
def checkout(price, rule): return rule.apply(price)
for rule in [NoDiscount(), PercentOff(10), FlatOff(150), FestivalOff()]: print(type(rule).__name__, checkout(1000, rule))print("FestivalOff", checkout(400, FestivalOff()))import java.util.List;
interface DiscountRule { int apply(int price);}
class NoDiscount implements DiscountRule { public int apply(int price) { return price; }}
class PercentOff implements DiscountRule { private int percent;
PercentOff(int percent) { this.percent = percent; }
public int apply(int price) { return price - price * percent / 100; }}
class FlatOff implements DiscountRule { private int amount;
FlatOff(int amount) { this.amount = amount; }
public int apply(int price) { return Math.max(0, price - amount); }}
class FestivalOff implements DiscountRule { public int apply(int price) { ________ // ← 25% off, but never more than 200 }}
public class Main { static int checkout(int price, DiscountRule rule) { return rule.apply(price); }
public static void main(String[] args) { List<DiscountRule> rules = List.of(new NoDiscount(), new PercentOff(10), new FlatOff(150), new FestivalOff()); for (DiscountRule rule : rules) { System.out.println(rule.getClass().getSimpleName() + " " + checkout(1000, rule)); } System.out.println("FestivalOff " + checkout(400, new FestivalOff())); }}When not to bother
- Say what the open/closed principle asks: add a new kind by writing new code, not by editing code that works.
- Spot the sign of trouble: a function with one if branch per kind, which every new kind must edit.
- Put each kind behind one interface: DiscountRule with apply, and one class per rule.
- Work out the festival rule: 25% off but never more than 200, so 1000 becomes 800 and 400 becomes 300.