All posts

· 8 min read

Path · Ch. 15

Strategy: change the algorithm without touching the rest of the program

The Strategy pattern turns a giant `if` or `switch` that picks how to calculate something into interchangeable pieces behind an interface. We apply it to the corner store's discounts and look at when it is not worth it.

On this page
  1. The problem: an if that picks the algorithm
  2. The idea: an interface and several implementations
  3. The cart does not know which rule it uses
  4. When NOT to use Strategy
  5. Mini-exercise: discount by minimum amount
  6. Suggested solution
  7. What you learned
  8. Stuck?

The corner store started with no discounts. Then came 10% off on Wednesdays, then 5 dollars off big purchases, then the employee discount. Every new rule went into the same function, and today nobody wants to open it because any change can break the other rules.

Strategy is the pattern for that moment: when one task (here, calculating the total) can be done in several ways and you want to switch the way without rewriting everything else.

The problem: an if that picks the algorithm

This is how the discount function usually ends up:

string[] kinds = { "none", "percentage", "fixed", "employee" };

foreach (string kind in kinds)
{
    decimal total = CalculateTotal(100.00m, kind);
    Console.WriteLine($"{kind}: {total:0.00}");
}

static decimal CalculateTotal(decimal subtotal, string discountKind)
{
    if (discountKind == "none")
    {
        return subtotal;
    }
    else if (discountKind == "percentage")
    {
        return subtotal - subtotal * 0.10m;
    }
    else if (discountKind == "fixed")
    {
        return Math.Max(0m, subtotal - 5.00m);
    }
    else if (discountKind == "employee")
    {
        return subtotal - subtotal * 0.20m;
    }

    throw new ArgumentException($"Unknown discount: {discountKind}");
}
none: 100.00
percentage: 90.00
fixed: 95.00
employee: 80.00

With four branches it is still readable. The problems show up over time:

  • Every new rule edits the same function. If two people add discounts at the same time, they collide in the same spot.
  • The rules are mixed together. To understand the employee discount you also have to read the other three.
  • There is repetition. percentage and employee are the same formula with a different number.
  • It is hard to test and to reuse. You cannot test the fixed discount without going through the if, and if another part of the program needs the same rule, it copies it.
  • The kind is a text. If you type "percentge" with a letter missing, the error shows up when the program runs, not when it compiles.

The idea: an interface and several implementations

Strategy separates two things. One is what is needed: “given a subtotal, tell me the total after the discount”. The other is how it is done, which changes with each rule. You write the first as an interface (chapter 10) and each rule becomes a class that implements it:

interface IDiscount
{
    decimal Apply(decimal subtotal);
    string Describe();
}

Each rule becomes a small class that does one thing. The ones that need a number receive it in the constructor, so percentage and employee stop being two copies of the same formula:

class NoDiscount : IDiscount
{
    public decimal Apply(decimal subtotal)
    {
        return subtotal;
    }

    public string Describe()
    {
        return "No discount";
    }
}

class PercentageDiscount : IDiscount
{
    private decimal percentage;

    public PercentageDiscount(decimal percentage)
    {
        this.percentage = percentage;
    }

    public decimal Apply(decimal subtotal)
    {
        return subtotal - subtotal * percentage;
    }

    public string Describe()
    {
        return $"{percentage * 100:0}% off";
    }
}

class FixedDiscount : IDiscount
{
    private decimal amount;

    public FixedDiscount(decimal amount)
    {
        this.amount = amount;
    }

    public decimal Apply(decimal subtotal)
    {
        return Math.Max(0m, subtotal - amount);
    }

    public string Describe()
    {
        return $"{amount:0.00} off";
    }
}

The cart does not know which rule it uses

Now the Cart holds a strategy and delegates the calculation to it. It has no if over discount kinds:

class Product
{
    public string Name { get; private set; }
    public decimal Price { get; private set; }

    public Product(string name, decimal price)
    {
        Name = name;
        Price = price;
    }
}

class Cart
{
    private List<Product> products = new List<Product>();

    public IDiscount Discount { get; set; } = new NoDiscount();

    public void Add(Product product)
    {
        products.Add(product);
    }

    public decimal Subtotal()
    {
        decimal sum = 0m;
        foreach (Product product in products)
        {
            sum += product.Price;
        }
        return sum;
    }

    public decimal Total()
    {
        return Discount.Apply(Subtotal());
    }
}

And here is everything working together. This is the complete program, with the classes above (IDiscount, NoDiscount, PercentageDiscount, FixedDiscount, Product and Cart) written after the main code:

Cart cart = new Cart();
cart.Add(new Product("Rice", 12.00m));
cart.Add(new Product("Beans", 2.50m));
cart.Add(new Product("Coffee", 8.50m));

Console.WriteLine($"Subtotal: {cart.Subtotal():0.00}");

List<IDiscount> discounts = new List<IDiscount>
{
    new NoDiscount(),
    new PercentageDiscount(0.10m),
    new FixedDiscount(5.00m),
    new PercentageDiscount(0.20m)
};

foreach (IDiscount discount in discounts)
{
    cart.Discount = discount;
    Console.WriteLine($"{discount.Describe()}: {cart.Total():0.00}");
}
Subtotal: 23.00
No discount: 23.00
10% off: 20.70
5.00 off: 18.00
20% off: 18.40

The loop at the end proves the pieces are interchangeable: same cart, same code, and only the strategy you assign changes. This is the polymorphism from chapter 10 put to work on something concrete.

Compare it with the earlier if. To add a new discount you write a new class. You do not touch Cart, you do not touch the other rules, and the compiler tells you if you misspell a name. If you want to pick the rule from a text that comes from a form or a file, that is where the factory from the previous chapter fits: a factory that returns the right IDiscount.

When NOT to use Strategy

Strategy costs files, classes and jumps while reading the code. Sometimes it is not worth it:

  • There are only two options and they will not change. A one-line if (isEmployee) is clearer than an interface with two classes. Move to Strategy when the branches grow or when you get the third one.
  • The algorithm is never swapped. If there is a single way to calculate something, you do not need an interface for it.
  • The branches share a lot of state. If each branch reads half a dozen variables from the program, moving them into classes means passing everything as parameters, and the result is heavier than the if.
  • What changes is data, not behavior. PercentageDiscount(0.10m) and PercentageDiscount(0.20m) are the same class with a different number. Do not create one class per percentage.

The signal to move to Strategy is the one you felt above: every new rule forces you to edit the same function, and the rules get in each other’s way.

Mini-exercise: discount by minimum amount

Add a new rule to this program, MinimumAmountDiscount: its constructor takes a minimum amount and a reduction. If the subtotal reaches the minimum, subtract the reduction; otherwise return the subtotal unchanged. Try it with two carts:

  1. A cart with Rice (12.00), Beans (2.50) and Coffee (8.50), using MinimumAmountDiscount(20.00m, 3.00m).
  2. A cart with only the Coffee (8.50), using the same rule.

Product, Cart, IDiscount and NoDiscount are the same as above and do not change.

Suggested solution

The new class. It goes below the main program, together with IDiscount, NoDiscount, Product and Cart (copy those classes from the full program above; the other two strategies are not needed here):

class MinimumAmountDiscount : IDiscount
{
    private decimal minimumAmount;
    private decimal reduction;

    public MinimumAmountDiscount(decimal minimumAmount, decimal reduction)
    {
        this.minimumAmount = minimumAmount;
        this.reduction = reduction;
    }

    public decimal Apply(decimal subtotal)
    {
        if (subtotal >= minimumAmount)
        {
            return subtotal - reduction;
        }
        return subtotal;
    }

    public string Describe()
    {
        return $"{reduction:0.00} off from {minimumAmount:0.00}";
    }
}

And the main program, which replaces the one above and goes at the top of the file, before all the classes:

Cart big = new Cart();
big.Add(new Product("Rice", 12.00m));
big.Add(new Product("Beans", 2.50m));
big.Add(new Product("Coffee", 8.50m));
big.Discount = new MinimumAmountDiscount(20.00m, 3.00m);

Cart small = new Cart();
small.Add(new Product("Coffee", 8.50m));
small.Discount = new MinimumAmountDiscount(20.00m, 3.00m);

Console.WriteLine($"Big cart: {big.Total():0.00}");
Console.WriteLine($"Small cart: {small.Total():0.00}");
Big cart: 20.00
Small cart: 8.50

What I want you to notice: you added a complete rule and never opened Cart or any of the other three strategies.

What you learned

  • An if or switch that picks between several ways of calculating something gets hard to change as it grows.
  • Strategy puts the “what” in an interface and each “how” in a class that implements it.
  • The code that uses the strategy (the Cart) only knows the interface, so you can change the rule without touching it.
  • Do not use it with two stable options, a single algorithm, or when the only thing that changes is a number.

In the next chapter we cover Observer: what to do when a single change, like confirming an order, has to notify several parts of the program.

Stuck?

If a strategy does not compile or you do not see how it connects to the cart, DM me on Instagram or ask in the Discord community. Paste your code and the error you get, and we will look at it together.