What is an example where OCP is violated?
Before (OCP Violation):
public class DiscountCalculator
public decimal CalculateDiscount(string customerType)
if (customerType == "Regular") return 10;
if (customerType == "Premium") return 20;
if (customerType == "VIP") return 30;
return 0;
If you need to support a new customer type, you must modify this method — violating OCP.
After (OCP Compliant):
public interface IDiscountStrategy
decimal GetDiscount();
public class RegularCustomerDiscount : IDiscountStrategy
public decimal GetDiscount() => 10;
public class PremiumCustomerDiscount : IDiscountStrategy
public decimal GetDiscount() => 20;
public class VipCustomerDiscount : IDiscountStrategy
public decimal GetDiscount() => 30;
Now you can add new customer types without modifying existing code — just create a new
strategy.