Does the Open/Closed Principle mean you can never edit an existing class?
No. You still fix bugs and change requirements. OCP is about designing so that common kinds of change, such as adding a new variant, need new code instead of edits to old code.
Explain it simply
A railway timetable gets corrected when a mistake is found; that is a bug fix. But when a new train starts, you add a new row instead of rewriting every row. OCP is about making the second kind of change cheap and safe.
You also cannot predict every kind of change. A reasonable approach is to wait, see the first change, and then shape the code so the next change of that kind needs no edits.
Example
# Closed to the "new discount" change, open to extension
class Discount:
def apply(self, amount): raise NotImplementedError
class Festive(Discount):
def apply(self, amount): return amount * 0.9
class Student(Discount):
def apply(self, amount): return amount - 50
def final_price(amount, discount):
return discount.apply(amount)
print(final_price(1000, Festive())) # 900.0
print(final_price(1000, Student())) # 950Fixing a wrong 10% to 12% still edits Festive. That is a requirement change in one place, and it is fine.
What to say in the interview
"OCP does not forbid edits. It means that for anticipated kinds of change, such as new variants, I design extension points so I add code rather than modify tested code. Bug fixes and changed rules still edit the class that owns them."
Common mistakes
- Reading OCP as a rule that makes bug fixes illegal.