Which change best follows the Open/Closed Principle?
def price(order):
if order.type == "regular": return order.total
if order.type == "vip": return order.total * 0.9
# every new customer type edits this functionOptions
- Add another
ifbranch each time a new type appears - Introduce a
PricingStrategyinterface and add a class per new type (Correct option) - Move the function into a separate utility module
- Keep a global dictionary of discounts and edit it at runtime
Answer
Introduce a PricingStrategy interface and add new classes for new types
Why
Open/Closed means: open for extension, closed for modification. You should add new behavior by ADDING code, not by editing code that already works and is tested.
With a growing if/elif, every new customer type means editing (and risking) this function.
With a strategy interface, each type is its own small class; a new type is a new class and the old code stays untouched.
Remember
Add new behavior with new code, not by editing working code.