DesignTheSystem/dev
Code Design (LLD) 6 min read

Open to extension, closed to edits

Shape a design so a new requirement means adding code, not rewriting it.

What the change request measures

Every problem here ends with a new requirement. The grade counts how many existing classes you had to edit. Good designs absorb change by adding a class or an entry.

Where to leave room

Look for the axis most likely to vary: pricing, piece types, split rules, fee plans, dispatch rules. Put that axis behind an interface on day one. Keep the stable core (the board, the ledger) free of knowledge about the variants.

Do not add interfaces for things that are unlikely to change. Every abstraction has a cost.

Key takeaways

  • Find the axis of change.
  • Put that axis behind an interface.
  • Leave the stable core unaware of variants.

Hands-on coding exercise

Checkout applies a list of discount rules; it is finished and must not change. Add a new rule, BuyXGetOneFree: for every X+1 units of a product, one is free.

"Buy 2, get 1 free" on 7 pens at 10 each: two free pens, so 20 off.

interface Line {
  sku: string;
  price: number;
  qty: number;
}

interface DiscountRule {
  discount(lines: Line[]): number;
}

// Finished: don't change this class
class Checkout {
  constructor(private readonly rules: DiscountRule[]) {}
  total(lines: Line[]): number {
    const gross = lines.reduce((s, l) => s + l.price * l.qty, 0);
    const off = this.rules.reduce((s, r) => s + r.discount(lines), 0);
    return Math.max(0, gross - off);
  }
}

class BuyXGetOneFree implements DiscountRule {
  constructor(private readonly sku: string, private readonly x: number) {}

  discount(lines: Line[]): 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. Electric vehicles need a new rate. Which design changes fewest classes?
  2. Should every class have an interface "just in case"?

Continue learning