SOLID: O — Open/Closed Principle
Code should be open for extension but closed for modification: add new behaviour by adding code, not by editing code that already works.
Why it matters
Every time a new type of thing appears (a new payment method, a new discount), developers edit the same big if/else, and each edit risks breaking cases that already worked.
The idea
A long if/elif chain on type ('if card … elif paypal …') must be edited every time a new case appears, which risks breaking the old cases. Instead, depend on an interface and add one new class for each new case.
A power strip: you add a new device by plugging it in, without rewiring the house.
A power strip has a fixed number of sockets, designed in advance. You can't predict every future change, so apply this where variation is likely, not everywhere.
How it works
- Find the code that switches on a type: if kind == 'sale' … elif kind == 'student' …
- Define an interface for the behaviour that varies: apply(price).
- Move each branch into its own class that implements the interface.
- The main code just calls rule.apply(price) for every rule it's given.
- A new discount is a new class. The main code never changes.
Example
A price calculator takes a list of discount rules. Adding a 'student discount' means adding one new rule class, with no change to the calculator.
Key points
- Replace 'switch on type' with polymorphism.
- Strategy, Decorator and plug-in designs all follow this principle.
- Protects tested code from new changes.
Common mistakes
- Adding abstractions for variations that will never happen.
- Still having to edit one central if/else to create the new class. Use a registry or configuration instead.
Not true: The open/closed principle says to add an abstraction for every variation you can imagine.
In fact: Every abstraction costs effort to read and maintain. Add one when a real variation appears, not for changes that may never come.
In the interview
Open/closed means I can add behaviour without editing existing code — for example, new discount types as new classes behind a DiscountRule interface, instead of a growing if/else chain.
Part of Unit 5: Low-level design: OOP and SOLID in the free System Design course.