Menu

O: Open/Closed Principle (SOLID Principles with Examples)
πŸ“°

O: Open/Closed Principle (SOLID Principles with Examples)

DEV Community: dotnetΒ·DIVAKAR UPADHYAYΒ·1 day ago
#jUGplFPY
#devtodotnet#devto#dev#type#decimal
Reading 0:00
15s threshold

πŸ‘‰ 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…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.