π Full lesson with practice questions on DevLadder (free, lesson 2 of 8 in the SOLID Principles with Examples course)
Software entities should be open for extension, closed for modification : add new behaviour by adding code, not by editing tested code.
// β Every new customer type edits this method public decimal Discount ( string type , decimal amount ) => type switch { "Regular" => amount * 0.05m , "Gold" => amount * 0.10m , "Platinum" => amount * 0.15m , // edit again next quarter... _ => 0 } ;
// β
New type = new class; existing code untouched (Strategy pattern) public interface IDiscountRule { string Type { get ; } decimal Apply ( decimal amount ) ; } public class GoldDiscount : IDiscountRule { public string Type => "Gold" ; public decimal Apply ( decimal a ) => a * 0.10m ; } public class PlatinumDiscount : IDiscountRule { public string Type => "Platinum" ; public decimal Apply ( decimal a ) => a * 0.15m ; }
public class DiscountService ( IEnumerable < IDiscountRule > rules ) { public decimalβ¦