Problem Statement
When software modules are changed directly to add new features, existing code can break and cause bugs. This makes the system fragile and hard to maintain as it grows.
┌───────────────┐ ┌───────────────┐
│ Existing │ │ New Feature │
│ Module │──────▶│ Module │
│ (Closed) │ │ (Extension) │
└───────────────┘ └───────────────┘
▲ │
│ │
└──────────────────────┘This diagram shows the existing module that is closed for changes but open to extensions through new modules that add features.
### Before (violates Open/Closed Principle): class DiscountCalculator: def calculate(self, customer_type, amount): if customer_type == 'regular': return amount * 0.9 elif customer_type == 'vip': return amount * 0.8 # Adding new customer types requires modifying this method ### After (applies Open/Closed Principle): from abc import ABC, abstractmethod class DiscountStrategy(ABC): @abstractmethod def calculate(self, amount): pass class RegularDiscount(DiscountStrategy): def calculate(self, amount): return amount * 0.9 class VIPDiscount(DiscountStrategy): def calculate(self, amount): return amount * 0.8 class DiscountCalculator: def __init__(self, strategy: DiscountStrategy): self.strategy = strategy def calculate(self, amount): return self.strategy.calculate(amount) # To add a new discount, create a new class without changing DiscountCalculator