Before you start
Open/Closed is the SOLID principle that pays off the most in design interviews. Interviewers add new requirements while you're working. Candidates whose code is closed for modification handle those requirements with a smile. Candidates whose code is open for modification start rewriting what they already have and hoping nothing breaks.
The exact definition
Bertrand Meyer's original words from 1988:
"Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification."
Open for extension — you can add new behavior. Closed for modification — you don't have to edit existing code to do it.
Polymorphism (you learned it in module 1) is what makes both true at once. Every "new behavior" is a new subclass. Existing classes stay untouched.
What if/elif chains cost you over time
Watch what happens in a real codebase using if/elif on
type:
- Year 1: One if/elif branch, three cases. Fine.
- Year 2: Nine cases across six methods. Copied everywhere.
- Year 3: You need to change how "student" works. You have to find every place that mentions "student" and update them all consistently. Miss one → subtle bug.
- Year 4: A junior adds "faculty" but forgets to update the export function. Broken CSV file in production.
Polymorphism turns "the student behavior is scattered
across six files" into "the student behavior is on
StudentDiscount". One class, one place to change.
The interview stress test
Watch for this in every design interview:
- Minute 15 — "Design a discount system for our e-commerce app"
- Minute 30 — you've drawn Regular / Student / Senior classes
- Minute 32 — "What about a Platinum tier at 30% off?"
If your answer is "add a new class, no existing code changes", you're showing OCP fluency. If your answer is "let me edit the calculator to add another case", you're failing an invisible test.
Every design problem has this shape. Parking lot fees, vending machine categories, notification channels, chess piece moves — all of them get "add a new subtype" requirements. All of them have the same right answer.
About the AST test
The last test in this lesson reads your
DiscountCalculator.apply method's source code and
rejects it if it contains isinstance() or type(). Not
because those functions are bad in general — but in this
specific spot, using them means dispatching on type, which
is exactly the smell OCP is meant to remove.
It's a strict version of the "did you actually fix the problem?" check.