Roadmap › SOLID Principles with Examples › Module: S and O
Lessons in this course (8)

2. O — Open/Closed Principle

Basic★ Must knowLesson 2 of 8

Software entities should be open for extension, closed for modification: add new behaviour by adding code, not by editing tested code.

csharp
// ❌ 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 Discount(string type, decimal amount) =>
        rules.FirstOrDefault(r => r.Type == type)?.Apply(amount) ?? 0;
}
// Program.cs
builder.Services.AddSingleton<IDiscountRule, GoldDiscount>();
builder.Services.AddSingleton<IDiscountRule, PlatinumDiscount>();

ASP.NET Core itself is OCP: you extend the pipeline by adding middleware, filters and services, without editing the framework.