DesignTheSystem/dev
Code Design (LLD) 6 min read

Strategy: swap behaviour, not code

Replace an if/else on a type with interchangeable strategy classes.

The smell

A method with if (type === "EQUAL") … else if (type === "EXACT") … grows a branch for every new type, and every change risks the others.

The fix

Define an interface for the varying behaviour and one class per variant. The caller picks a strategy (often from a lookup table) and calls it. A new variant is a new class; nothing else changes.

interface SplitStrategy {
  owed(amount: number, input: Split): Map<string, number>;
}
const STRATEGIES: Record<Split["type"], SplitStrategy> = {
  EQUAL: new EqualSplit(),
  EXACT: new ExactSplit(),
};

Key takeaways

  • Branching on a type is the signal.
  • Interface plus one class per variant.
  • Adding a variant should not edit existing classes.

Hands-on coding exercise

Checkout charges shipping, and the rule depends on the option the buyer picks. Standard: 50, free when the order is 500 or more. Express: always 120.

Each rule is a class with the same method; Checkout is given one and never branches on which.

interface ShippingRule {
  cost(orderTotal: number): number;
}

class StandardShipping implements ShippingRule {
  cost(orderTotal: number): number {
    throw new Error("Not implemented");
  }
}

class ExpressShipping implements ShippingRule {
  cost(orderTotal: number): number {
    throw new Error("Not implemented");
  }
}

class Checkout {
  constructor(private readonly shipping: ShippingRule) {}

  total(orderTotal: number): number {
    throw new Error("Not implemented");
  }
}

Run your solution against 4 automated tests in the interactive workspace:

Check your understanding

Answer these questions interactively to test what you learned and track progress on your skill map:

  1. You must add a SHARES split. With the strategy pattern, what changes?
  2. When is a strategy overkill?

Continue learning