Repaso
Español
Design & PracticesIntermediateDP-02

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 function

Options

  1. Add another if branch each time a new type appears
  2. Introduce a PricingStrategy interface and add a class per new type (Correct option)
  3. Move the function into a separate utility module
  4. 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.

Key terms

Practice this question in Repaso