Weekly Deals: Pass the Rule In

When this week's deal is picked by a switch inside checkout, every new deal means editing the code that handles the money; handing the deal into checkout as a function, the Strategy pattern in its simplest form, lets a new deal be written without touching checkout at all.

Apprentice · OOP · Updated

By

After this lesson you can

  • Pass a rule into code as a function, so a new rule needs no change to the code that uses it
  • Spot the smells that point to Strategy: a growing switch on a rule's name inside code that shouldn't change

Key takeaways

  • The smell: a switch on a rule's name that grows every week, inside code that shouldn't change.
  • The cause: the part that changes (the deal) lives inside the part that doesn't (checkout).
  • The fix: hand the rule in as a function. Checkout calls whatever deal it's given, and a new deal is a new function.
  • One way of doing a job, handed in so it can be swapped, is called a strategy. Pass 2 grows it into a class when a rule needs its own data.

Before this: Meet the Bakery App, and passing a function as a value (a lambda, or an arrow function).

The owner's second wish: a new deal every week. This week it's $2 off every box of cupcakes. Next week, every third cookie box is free. The week after, something nobody has thought of yet. Checkout already works out the price, so the deals went into checkout. By the third week, there's a problem with that, and this lesson ends with a pattern called a strategy in its simplest form.

The symptom: checkout changes every week

Here is checkout after three weeks of deals. It's handed the order and the deal's name, and works out the price. A customer's order of a cake, two boxes of cupcakes and three cookie boxes comes to $78 before any deal:

List<IProduct> order = new List<IProduct> { new Cake(), new Cupcakes(), new Cupcakes(), new CookieBox(), new CookieBox(), new CookieBox() };
foreach (string deal in new List<string> { "none", "cupcakes-2-off", "third-cookie-box-free" })
{
    Console.WriteLine(quot;{deal}: ${Checkout(order, deal)}");
}

int Checkout(List<IProduct> products, string deal)
{
    int subtotal = products.Sum(product => product.Price);
    int discount = 0;
    if (deal == "cupcakes-2-off")
    {
        discount = 2 * Count(products, "Cupcakes");
    }
    else if (deal == "third-cookie-box-free")
    {
        discount = 8 * (Count(products, "Cookie box") / 3);
    }
    return subtotal - discount;
}

int Count(List<IProduct> products, string name) => products.Count(product => product.Name == name);

interface IProduct
{
    string Name { get; }
    int Price { get; }
}

class Cake : IProduct { public string Name => "Cake"; public int Price => 30; }
class Cupcakes : IProduct { public string Name => "Cupcakes"; public int Price => 12; }
class CookieBox : IProduct { public string Name => "Cookie box"; public int Price => 8; }
none: $78
cupcakes-2-off: $74
third-cookie-box-free: $70
interface Product {
    String name();
    int price();
}

class Cake implements Product { public String name() { return "Cake"; } public int price() { return 30; } }
class Cupcakes implements Product { public String name() { return "Cupcakes"; } public int price() { return 12; } }
class CookieBox implements Product { public String name() { return "Cookie box"; } public int price() { return 8; } }

int count(List<Product> products, String name) {
    int count = 0;
    for (Product product : products) {
        if (product.name().equals(name)) { count++; }
    }
    return count;
}

int checkout(List<Product> products, String deal) {
    int subtotal = 0;
    for (Product product : products) { subtotal += product.price(); }
    int discount = 0;
    if (deal.equals("cupcakes-2-off")) {
        discount = 2 * count(products, "Cupcakes");
    } else if (deal.equals("third-cookie-box-free")) {
        discount = 8 * (count(products, "Cookie box") / 3);
    }
    return subtotal - discount;
}

void main() {
    List<Product> order = List.of(new Cake(), new Cupcakes(), new Cupcakes(), new CookieBox(), new CookieBox(), new CookieBox());
    for (String deal : List.of("none", "cupcakes-2-off", "third-cookie-box-free")) {
        IO.println(deal + ": quot; + checkout(order, deal));
    }
}
none: $78
cupcakes-2-off: $74
third-cookie-box-free: $70
class Cake:
    name = "Cake"
    price = 30


class Cupcakes:
    name = "Cupcakes"
    price = 12


class CookieBox:
    name = "Cookie box"
    price = 8


def count(products, name):
    return sum(1 for product in products if product.name == name)


def checkout(products, deal):
    subtotal = sum(product.price for product in products)
    discount = 0
    if deal == "cupcakes-2-off":
        discount = 2 * count(products, "Cupcakes")
    elif deal == "third-cookie-box-free":
        discount = 8 * (count(products, "Cookie box") // 3)
    return subtotal - discount


order = [Cake(), Cupcakes(), Cupcakes(), CookieBox(), CookieBox(), CookieBox()]
for deal in ["none", "cupcakes-2-off", "third-cookie-box-free"]:
    print(f"{deal}: ${checkout(order, deal)}")
none: $78
cupcakes-2-off: $74
third-cookie-box-free: $70
class Cake { name = "Cake"; price = 30; }
class Cupcakes { name = "Cupcakes"; price = 12; }
class CookieBox { name = "Cookie box"; price = 8; }

function count(products, name) {
  return products.filter((product) => product.name === name).length;
}

function checkout(products, deal) {
  let subtotal = 0;
  for (const product of products) { subtotal += product.price; }
  let discount = 0;
  if (deal === "cupcakes-2-off") {
    discount = 2 * count(products, "Cupcakes");
  } else if (deal === "third-cookie-box-free") {
    discount = 8 * Math.floor(count(products, "Cookie box") / 3);
  }
  return subtotal - discount;
}

const order = [new Cake(), new Cupcakes(), new Cupcakes(), new CookieBox(), new CookieBox(), new CookieBox()];
for (const deal of ["none", "cupcakes-2-off", "third-cookie-box-free"]) {
  console.log(`${deal}: ${checkout(order, deal)}`);
}
none: $78
cupcakes-2-off: $74
third-cookie-box-free: $70
interface Product {
  name: string;
  price: number;
}

class Cake implements Product { name = "Cake"; price = 30; }
class Cupcakes implements Product { name = "Cupcakes"; price = 12; }
class CookieBox implements Product { name = "Cookie box"; price = 8; }

function count(products: Product[], name: string): number {
  return products.filter((product) => product.name === name).length;
}

function checkout(products: Product[], deal: string): number {
  let subtotal = 0;
  for (const product of products) { subtotal += product.price; }
  let discount = 0;
  if (deal === "cupcakes-2-off") {
    discount = 2 * count(products, "Cupcakes");
  } else if (deal === "third-cookie-box-free") {
    discount = 8 * Math.floor(count(products, "Cookie box") / 3);
  }
  return subtotal - discount;
}

const order = [new Cake(), new Cupcakes(), new Cupcakes(), new CookieBox(), new CookieBox(), new CookieBox()];
for (const deal of ["none", "cupcakes-2-off", "third-cookie-box-free"]) {
  console.log(`${deal}: ${checkout(order, deal)}`);
}
none: $78
cupcakes-2-off: $74
third-cookie-box-free: $70

It works. But follow it forward a month: every week someone opens checkout, the code that takes the customer's money, and adds another else if. Old deals stay in it, because nobody is sure they're never used. A typo in this week's deal can break last week's.

  • The symptom: a switch (or if chain) on a rule's name that grows every week, inside code that should almost never change.
  • The cause: the part that changes (the deal) lives inside the part that doesn't (checkout).

What would you try?

Keep adding else if lines. That's what's happening, and it's the problem: the riskiest code in the app is edited the most.

A true-or-false flag for each deal, such as cupcakesDeal and cookieDeal. Now every deal is a parameter on checkout, and checkout still has to know them all.

Copy checkout once for each deal: checkoutCupcakeWeek, checkoutCookieWeek. Each copy has the subtotal code in it, so a fix to the subtotal has to be made in every copy.

What would really help is if checkout didn't have to know what the deals are at all, only that there is one, and that it can ask it "how much comes off this order?"

The fix: hand the deal in

A camera works this way. It has one shutter button, and a dial for the mode: portrait, night, sports. The shutter button does the same job every time; the mode you hand it decides how. A new mode doesn't need a new shutter button.

A camera seen from above, with one shutter button and a mode dial beside it whose positions are labeled Portrait, Night and Sports, the dial turned to Night

In code, the dial is a function handed into checkout. Each deal is a small function that takes the order and answers one question: how much comes off? Checkout works out the subtotal, asks the deal it was given, and subtracts. A function that takes another function like this is called a higher-order function.

A role diagram: checkout, the code that never changes, asks "how much off?" of this week's deal, a function. Three deals (no deal, $2 off cupcakes, third cookie box free) can fill that place, all inside a dashed fence labeled "what changes: the deal, every week"

List<IProduct> order = new List<IProduct> { new Cake(), new Cupcakes(), new Cupcakes(), new CookieBox(), new CookieBox(), new CookieBox() };
List<(string Name, Func<List<IProduct>, int> Deal)> deals = new List<(string, Func<List<IProduct>, int>)>
{
    ("none", NoDeal),
    ("cupcakes-2-off", CupcakesTwoOff),
    ("third-cookie-box-free", ThirdCookieBoxFree)
};
foreach ((string name, Func<List<IProduct>, int> deal) in deals)
{
    Console.WriteLine(quot;{name}: ${Checkout(order, deal)}");
}

// Checkout never changes again: it asks whatever deal it's handed.
int Checkout(List<IProduct> products, Func<List<IProduct>, int> deal)
{
    int subtotal = products.Sum(product => product.Price);
    return subtotal - deal(products);
}

// Each deal answers one question: how much comes off this order?
int NoDeal(List<IProduct> products) => 0;
int CupcakesTwoOff(List<IProduct> products) => 2 * Count(products, "Cupcakes");
int ThirdCookieBoxFree(List<IProduct> products) => 8 * (Count(products, "Cookie box") / 3);

int Count(List<IProduct> products, string name) => products.Count(product => product.Name == name);

interface IProduct
{
    string Name { get; }
    int Price { get; }
}

class Cake : IProduct { public string Name => "Cake"; public int Price => 30; }
class Cupcakes : IProduct { public string Name => "Cupcakes"; public int Price => 12; }
class CookieBox : IProduct { public string Name => "Cookie box"; public int Price => 8; }
none: $78
cupcakes-2-off: $74
third-cookie-box-free: $70
interface Product {
    String name();
    int price();
}

class Cake implements Product { public String name() { return "Cake"; } public int price() { return 30; } }
class Cupcakes implements Product { public String name() { return "Cupcakes"; } public int price() { return 12; } }
class CookieBox implements Product { public String name() { return "Cookie box"; } public int price() { return 8; } }

// A deal answers one question: how much comes off this order?
interface Deal {
    int discount(List<Product> products);
}

int count(List<Product> products, String name) {
    int count = 0;
    for (Product product : products) {
        if (product.name().equals(name)) { count++; }
    }
    return count;
}

// Checkout never changes again: it asks whatever deal it's handed.
int checkout(List<Product> products, Deal deal) {
    int subtotal = 0;
    for (Product product : products) { subtotal += product.price(); }
    return subtotal - deal.discount(products);
}

void main() {
    List<Product> order = List.of(new Cake(), new Cupcakes(), new Cupcakes(), new CookieBox(), new CookieBox(), new CookieBox());
    Map<String, Deal> deals = new LinkedHashMap<>();
    deals.put("none", products -> 0);
    deals.put("cupcakes-2-off", products -> 2 * count(products, "Cupcakes"));
    deals.put("third-cookie-box-free", products -> 8 * (count(products, "Cookie box") / 3));
    for (String name : deals.keySet()) {
        IO.println(name + ": quot; + checkout(order, deals.get(name)));
    }
}
none: $78
cupcakes-2-off: $74
third-cookie-box-free: $70
class Cake:
    name = "Cake"
    price = 30


class Cupcakes:
    name = "Cupcakes"
    price = 12


class CookieBox:
    name = "Cookie box"
    price = 8


def count(products, name):
    return sum(1 for product in products if product.name == name)


def checkout(products, deal):
    """Checkout never changes again: it asks whatever deal it's handed."""
    subtotal = sum(product.price for product in products)
    return subtotal - deal(products)


# Each deal answers one question: how much comes off this order?
def no_deal(products):
    return 0


def cupcakes_two_off(products):
    return 2 * count(products, "Cupcakes")


def third_cookie_box_free(products):
    return 8 * (count(products, "Cookie box") // 3)


order = [Cake(), Cupcakes(), Cupcakes(), CookieBox(), CookieBox(), CookieBox()]
deals = {"none": no_deal, "cupcakes-2-off": cupcakes_two_off, "third-cookie-box-free": third_cookie_box_free}
for name, deal in deals.items():
    print(f"{name}: ${checkout(order, deal)}")
none: $78
cupcakes-2-off: $74
third-cookie-box-free: $70
class Cake { name = "Cake"; price = 30; }
class Cupcakes { name = "Cupcakes"; price = 12; }
class CookieBox { name = "Cookie box"; price = 8; }

function count(products, name) {
  return products.filter((product) => product.name === name).length;
}

// Checkout never changes again: it asks whatever deal it's handed.
function checkout(products, deal) {
  let subtotal = 0;
  for (const product of products) { subtotal += product.price; }
  return subtotal - deal(products);
}

// Each deal answers one question: how much comes off this order?
const deals = new Map([
  ["none", (products) => 0],
  ["cupcakes-2-off", (products) => 2 * count(products, "Cupcakes")],
  ["third-cookie-box-free", (products) => 8 * Math.floor(count(products, "Cookie box") / 3)],
]);

const order = [new Cake(), new Cupcakes(), new Cupcakes(), new CookieBox(), new CookieBox(), new CookieBox()];
for (const [name, deal] of deals) {
  console.log(`${name}: ${checkout(order, deal)}`);
}
none: $78
cupcakes-2-off: $74
third-cookie-box-free: $70
interface Product {
  name: string;
  price: number;
}

class Cake implements Product { name = "Cake"; price = 30; }
class Cupcakes implements Product { name = "Cupcakes"; price = 12; }
class CookieBox implements Product { name = "Cookie box"; price = 8; }

// A deal answers one question: how much comes off this order?
type Deal = (products: Product[]) => number;

function count(products: Product[], name: string): number {
  return products.filter((product) => product.name === name).length;
}

// Checkout never changes again: it asks whatever deal it's handed.
function checkout(products: Product[], deal: Deal): number {
  let subtotal = 0;
  for (const product of products) { subtotal += product.price; }
  return subtotal - deal(products);
}

const deals = new Map<string, Deal>([
  ["none", (products) => 0],
  ["cupcakes-2-off", (products) => 2 * count(products, "Cupcakes")],
  ["third-cookie-box-free", (products) => 8 * Math.floor(count(products, "Cookie box") / 3)],
]);

const order = [new Cake(), new Cupcakes(), new Cupcakes(), new CookieBox(), new CookieBox(), new CookieBox()];
for (const [name, deal] of deals) {
  console.log(`${name}: ${checkout(order, deal)}`);
}
none: $78
cupcakes-2-off: $74
third-cookie-box-free: $70

Same prices, and checkout is now three lines that won't change again. Next week's deal is one new function, written anywhere, and checkout never knows its name. The deals live in a dictionary from name to function, the same move as the last chapter's makers, so the counter tablet can still pick this week's deal by its name.

Try it. Add a fourth deal, "$5 off orders over $60", without touching checkout. The order above should cost $73 with it.

Where the languages differ. Java names the shape of a deal with a small interface, Deal, with one method; any lambda with the same shape fits it. C# uses the built-in Func<List<IProduct>, int>, TypeScript a type, and Python and JavaScript pass the function.

How it got its name

One way of doing a job, kept separate so it can be swapped for another, is a strategy, and code built around handing one in follows the Strategy pattern. The original book wrote each strategy as a class with one method. Today, when the strategy is a single rule like this week's deal, a function says the same thing in one line. Pass 2 meets a rule that needs more than a function (its own data and several methods), and the strategy grows into a class there.

Where you've already used it

  • Sorting with your own rule: sorted(cakes, key=...) in Python, list.Sort((a, b) => ...) in C#, array.sort((a, b) => ...) in JavaScript, a Comparator in Java. The sort is the checkout; the rule you hand it is the deal.
  • filter and map: the list does the looping, and you hand in what to do with each item.
  • A button's click handler: the button is the same every time, and you hand in what clicking it does.

When not to use it

  • When there's one rule that never changes. A fixed 10% student discount doesn't need to be handed in; it can be written.
  • When there are two rules, fixed for good. A plain if reads fine. Reach for this when the rules keep coming.

The cost is one more jump for the reader: to know what checkout charges, you have to know which deal it was handed.

How often you'll meet it: every day, in its function form (our estimate: sorting, filtering and event handlers alone make it common in every language).

Check yourself

2 questions to try on the lesson page.

So what

When the part of the code that changes every week sits inside the part that shouldn't change, hand it in instead. Checkout stops changing, and each new rule is a small function of its own. That's the Strategy pattern, in the form you'll use most.

Key terms

Cheat sheets