Open/closed principle
medium 55 minCode should be open for extension and closed for modification: a new kind of thing arrives as new code, and the code that already works stays as it is.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Objects at run time: what is edited, what is only added, and where the promises are checked.
Operations
The growing chain
One method knows every discount. Watch who is hit by the next one.
Step 1 of 5
Two branches
Premium and VIP. Short, clear, and correct. Three parts of the program use it.
Step 1: Two branches
def total(self, cart): cut = 0 if cart.tier == "premium": cut = 20 elif cart.tier == "vip": cut = 30 if cart.student: cut = 15 return cart.subtotal * (100 - cut) // 100- Good for
- Two or three kinds
- Costs
- Every kind is an edit
- Branches for n kinds
- n
Look at the history of the file. The same kind of commit three times is your axis.
In the real world
The same open/closed principle doing real jobs. Pick one and step through it.
A closed case with open ports. Every device brings its own ability.
Step 1 of 7
The computer
The case is closed and tested. The ports are the extension points.
Step 1: The computer
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A class where a value would do
majorRegular, premium and VIP differ only in a number. Three classes hide that.
Wrongclass PremiumCustomer(Customer): def discount(self): return 20RightTierDiscount("premium", 20)The core asks for the type
criticalOne
isinstanceand the core must be edited for the next special rule.Wrongcut = rule.amount(cart)if isinstance(rule, Coupon): cut = min(cut, left)Rightcut = min(rule.amount(cart), left) # for all rulesRegistration order decides
criticalImports run in another order on another machine, and the price changes.
Wrongfor rule in registry.all(): # as imported price = rule.apply(price)Rightrules = sorted(all_rules, key=lambda r: (r.stage, r.priority, r.name))A contract without limits
majorThe method exists, but a rule returns -500 or 12.5, and the error shows somewhere else.
Wrongleft -= rule.amount(cart)Rightcut = rule.amount(cart)if cut < 0: raise ValueError(rule.name)left -= min(cut, left)Sockets for a future that does not come
minorInterface, factory and registry for one class: every reader takes the long way.
Wrongexporter = ExporterFactory.create("pdf") # the only oneRightwrite_pdf(report, out)Swallowing a required failure
criticalIsolation is right for metrics and a security hole for authentication.
Wrongtry: plugin.execute(request)except Exception: passRightexcept Exception: failures[plugin.name] += 1 if plugin.required: raise
Interview tips
Point at lines
- Show which lines change for a new kind
- Show which stay
- Offer to add one live
Name the axis
- Closed against new discounts
- Not against new operations
- Say why this axis
Guard the socket
- Check limits in the core
- Order and groups explicit
- One contract test for all
Know when not
- One example: plain code
- Only values: a table
- Closed set: a switch