All posts

· 10 min read

Path · Ch. 12

SOLID for beginners: five rules for code that survives change

A short before and after C# example for each SOLID principle, using a corner store as the running thread. We also cover when not to apply them.

On this page
  1. S: one class, one reason to change
  2. O: add without editing
  3. L: a substitute must not surprise you
  4. I: small interfaces
  5. D: depend on the idea, not the detail
  6. When not to apply them
  7. Exercise
  8. Suggested solution
  9. Recap

In the last chapter we looked at common OOP mistakes: classes that do everything, inheritance for everything, objects that are just data. They share one thing: the code works today, but every change is scary. Part 3 starts with five ideas that help you avoid that.

They are called SOLID, an acronym where each letter is a principle. They are not laws and you do not need to follow them 100% of the time. They are guidelines so that when a change request arrives, you touch few things and do not break the rest.

We will use a corner store: products, orders, discounts, payments and notifications. Every example is a full Program.cs you can paste into a new project (dotnet new console). Types go below the statements at the top, as in earlier chapters. Two new bits: record Product(string Name, decimal Price); is a short way to declare a data class with those two properties, filled in with new Product("Coffee", 3.50m). And _products.Sum(p => p.Price) adds up the Price of every product in the list; p => p.Price means “for each p, take its Price”.

S: one class, one reason to change

Single responsibility. A class should have one reason to change. Here Order calculates the total and also knows how to print the receipt:

var order = new Order();
order.Add(new Product("Coffee", 3.50m));
order.Add(new Product("Bread", 1.25m));
order.PrintReceipt();

record Product(string Name, decimal Price);

class Order
{
    private readonly List<Product> _products = new();

    public void Add(Product product) => _products.Add(product);

    public decimal Total() => _products.Sum(p => p.Price);

    public void PrintReceipt()
    {
        foreach (var p in _products)
            Console.WriteLine($"{p.Name}: {p.Price:0.00}");
        Console.WriteLine($"Total: {Total():0.00}");
    }
}
Coffee: 3.50
Bread: 1.25
Total: 4.75

It works. The trouble starts when someone asks for a different receipt format: you open Order, which also holds the total rules. Two reasons to change in the same class. Let’s split it:

var order = new Order();
order.Add(new Product("Coffee", 3.50m));
order.Add(new Product("Bread", 1.25m));
new Receipt().Print(order);

record Product(string Name, decimal Price);

class Order
{
    private readonly List<Product> _products = new();

    // IReadOnlyList: callers can read the list but not modify it.
    public IReadOnlyList<Product> Products => _products;

    public void Add(Product product) => _products.Add(product);

    public decimal Total() => _products.Sum(p => p.Price);
}

class Receipt
{
    public void Print(Order order)
    {
        foreach (var p in order.Products)
            Console.WriteLine($"{p.Name}: {p.Price:0.00}");
        Console.WriteLine($"Total: {order.Total():0.00}");
    }
}

Same output. Now changing the receipt does not touch the order rules.

O: add without editing

Open/closed. Code should grow by adding new pieces, not by editing the ones that already work. This switch grows with every customer type:

Console.WriteLine($"{FinalPrice(100m, "student"):0.00}");
Console.WriteLine($"{FinalPrice(100m, "neighbor"):0.00}");
Console.WriteLine($"{FinalPrice(100m, "none"):0.00}");

static decimal FinalPrice(decimal subtotal, string customerType)
{
    switch (customerType)
    {
        case "student": return subtotal * 0.90m;
        case "neighbor": return subtotal * 0.95m;
        default: return subtotal;
    }
}
90.00
95.00
100.00

Each new discount is another case in a function that is already in production. With an interface, each discount is a new class:

var discounts = new Dictionary<string, IDiscount>
{
    ["student"] = new PercentageDiscount(0.10m),
    ["neighbor"] = new PercentageDiscount(0.05m),
    ["none"] = new NoDiscount()
};

foreach (var pair in discounts)
    Console.WriteLine($"{pair.Key}: {pair.Value.Apply(100m):0.00}");

interface IDiscount
{
    decimal Apply(decimal subtotal);
}

class PercentageDiscount : IDiscount
{
    private readonly decimal _percentage;

    public PercentageDiscount(decimal percentage)
    {
        _percentage = percentage;
    }

    public decimal Apply(decimal subtotal) => subtotal * (1 - _percentage);
}

class NoDiscount : IDiscount
{
    public decimal Apply(decimal subtotal) => subtotal;
}
student: 90.00
neighbor: 95.00
none: 100.00

If tomorrow there is a “buy 3, pay for 2” deal, you write ThreeForTwoDiscount and the code that uses IDiscount never notices. This idea has its own name, and we will see it later in Part 3.

L: a substitute must not surprise you

Liskov substitution. If a class inherits from another or implements an interface, it must be usable wherever the original is expected without anything breaking. Here Card adds a rule that PaymentMethod never promised:

var methods = new List<PaymentMethod> { new Cash(), new Card() };

foreach (var method in methods)
{
    try
    {
        method.Charge(2.00m);
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine($"Failed: {ex.Message}");
    }
}

class PaymentMethod
{
    public virtual void Charge(decimal amount) => Console.WriteLine($"Charged {amount:0.00}");
}

class Cash : PaymentMethod { }

class Card : PaymentMethod
{
    public override void Charge(decimal amount)
    {
        if (amount < 5m)
            throw new InvalidOperationException("Minimum 5.00 with card");
        base.Charge(amount);
    }
}
Charged 2.00
Failed: Minimum 5.00 with card

Whoever receives a PaymentMethod cannot know that one of them blows up on small amounts. The fix is to put the rule in the contract, so every method expresses it the same way:

var methods = new List<IPaymentMethod> { new Cash(), new Card() };

foreach (var method in methods)
{
    if (method.CanCharge(2.00m))
        method.Charge(2.00m);
    else
        Console.WriteLine($"{method.Name} does not accept 2.00");
}

interface IPaymentMethod
{
    string Name { get; }
    bool CanCharge(decimal amount);
    void Charge(decimal amount);
}

class Cash : IPaymentMethod
{
    public string Name => "Cash";
    public bool CanCharge(decimal amount) => amount > 0;
    public void Charge(decimal amount) => Console.WriteLine($"{Name}: charged {amount:0.00}");
}

class Card : IPaymentMethod
{
    public string Name => "Card";
    public bool CanCharge(decimal amount) => amount >= 5m;
    public void Charge(decimal amount) => Console.WriteLine($"{Name}: charged {amount:0.00}");
}
Cash: charged 2.00
Card does not accept 2.00

(A property in an interface, like string Name { get; }, only says that every implementing class must have it.) A sign you are breaking Liskov: you see throw new NotSupportedException() inside a subclass, or an if (x is Card) in the code that uses it.

I: small interfaces

Interface segregation. Nobody should depend on methods they do not use. Picture a single IInventory interface with Find, Add and Remove. A price report that only looks things up would still receive all three methods, and to test it you would have to implement every one.

The alternative is to split it by who uses it:

var inventory = new InMemoryInventory();
inventory.Add(new Product("Coffee", 3.50m));

var report = new PriceReport(inventory);
report.Print("Coffee");
report.Print("Bread");

record Product(string Name, decimal Price);

interface IProductFinder
{
    Product? Find(string name);
}

interface IInventoryEditor
{
    void Add(Product product);
    void Remove(string name);
}

class InMemoryInventory : IProductFinder, IInventoryEditor
{
    private readonly Dictionary<string, Product> _products = new();

    public Product? Find(string name) => _products.GetValueOrDefault(name);
    public void Add(Product product) => _products[product.Name] = product;
    public void Remove(string name) => _products.Remove(name);
}

class PriceReport
{
    private readonly IProductFinder _finder;

    public PriceReport(IProductFinder finder)
    {
        _finder = finder;
    }

    public void Print(string name)
    {
        var product = _finder.Find(name);
        Console.WriteLine(product is null
            ? $"{name}: not found"
            : $"{product.Name}: {product.Price:0.00}");
    }
}
Coffee: 3.50
Bread: not found

GetValueOrDefault(name) looks the key up in the dictionary and returns the value, or null if it is missing; that is why Find returns Product? (a product that may be absent). A class can implement several interfaces, and PriceReport only sees the one it needs. It can no longer delete products by accident.

D: depend on the idea, not the detail

Dependency inversion. Important classes should not build or know the details of the pieces they use; they should depend on an interface. Here Order creates its own notifier:

var order = new Order();
order.Confirm();

class EmailNotifier
{
    public void Send(string message) => Console.WriteLine($"Email: {message}");
}

class Order
{
    private readonly EmailNotifier _notifier = new();

    public void Confirm() => _notifier.Send("Order confirmed");
}

To switch to SMS, or to test Order without sending real emails, you have to edit Order. We invert it: Order asks for an interface and someone from outside hands it the piece.

var byEmail = new Order(new EmailNotifier());
byEmail.Confirm();

var bySms = new Order(new SmsNotifier());
bySms.Confirm();

interface INotifier
{
    void Send(string message);
}

class EmailNotifier : INotifier
{
    public void Send(string message) => Console.WriteLine($"Email: {message}");
}

class SmsNotifier : INotifier
{
    public void Send(string message) => Console.WriteLine($"SMS: {message}");
}

class Order
{
    private readonly INotifier _notifier;

    public Order(INotifier notifier)
    {
        _notifier = notifier;
    }

    public void Confirm() => _notifier.Send("Order confirmed");
}
Email: Order confirmed
SMS: Order confirmed

Order did not change to support SMS. This is the principle that pays off most in practice, because it lets you swap pieces and test them in isolation.

When not to apply them

This is what most tutorials skip. Every principle costs something: more types, more files, more jumps to follow the code. It is Mistake #2 from the previous chapter: more classes is not better design.

Do not apply them when:

  • The program is a script or a small tool you will throw away. A three-case switch nobody will extend is fine.
  • An interface would have one implementation and you have no concrete reason to expect another. Create it when the second one shows up, or when you need to test the first in isolation.
  • You do not understand the problem yet. A guessed abstraction usually comes out wrong and costs more to undo than a bit of duplication.

The signal to apply a principle is real pain: you change one thing and another breaks, a piece is hard to test, or you edit the same function every time a new requirement arrives. If you do not feel that pain, keep the code simple.

Exercise

This program calculates shipping cost with a switch:

Console.WriteLine($"{ShippingCost("pickup"):0.00}");
Console.WriteLine($"{ShippingCost("delivery"):0.00}");

static decimal ShippingCost(string type)
{
    switch (type)
    {
        case "pickup": return 0m;
        case "delivery": return 5.00m;
        default: throw new ArgumentException("Unknown shipping type");
    }
}
  1. Which principle helps here?
  2. Rewrite it so that adding “express delivery” does not require editing existing code. Each option must be able to report its name and its cost.

Suggested solution

The principle is open/closed. One IShipping interface and one class per option:

var options = new List<IShipping> { new Pickup(), new Delivery() };

foreach (var option in options)
    Console.WriteLine($"{option.Name}: {option.Cost():0.00}");

interface IShipping
{
    string Name { get; }
    decimal Cost();
}

class Pickup : IShipping
{
    public string Name => "Pickup";
    public decimal Cost() => 0m;
}

class Delivery : IShipping
{
    public string Name => "Delivery";
    public decimal Cost() => 5.00m;
}
Pickup: 0.00
Delivery: 5.00

To add express delivery you write an Express : IShipping class and put it in the list. Nothing above it is touched.

Recap

  • S: one class, one reason to change.
  • O: add behavior with new pieces, not by editing the ones that work.
  • L: a substitute must keep the promises of the original, no surprises.
  • I: small interfaces, sized for whoever uses them.
  • D: depend on interfaces and receive pieces from outside.
  • Apply them when change hurts, not in advance.

In the next chapter we talk about design patterns: named solutions to problems that keep coming back, and why you should recognize the problem before reaching for the pattern.

If you have questions, DM me on Instagram or ask in the Discord community.