Track 04 · Lesson 4 of 15Code that stays easy to change

Track 04 · Code that stays easy to change

O: Open/closed

Lesson 4 of 15· 7 min

Code should be open for extension and closed for modification. Adding a new kind of thing shouldn’t mean editing code that already works and is already tested. It’s the O in SOLID, the five principles that start with Single responsibility.

Add payment methods

Add three, then flip the switch

Product keeps asking for new ways to pay. Add them one by one.

Files touched

checkout.ts · unchanged
  • ✓ pays with card
  • ✓ pays with paypal

0

Edits to working, tested code

0

Payment tests failing

Add a payment method and watch which files change.

checkout.tsWithout it
// Every new payment method means editing this tested function
export function charge(method: string, amount: number) {
  switch (method) {
    case "card":
      return stripe.charge(amount)
    case "paypal":
      return paypal.pay(amount)
    case "crypto":            // added on Friday...
      wallet.reserve(amount)
      // ...and someone forgot the return. Falls through!
    case "bank":
      return bank.transfer(amount)
    default:
      throw new Error(`Unknown method ${method}`)
  }
}

Find the seam#

Look for code that grows a new branch every time the business grows: a switch on a type, a chain of if (kind === …). That list wants to be a seam: a small interface (PaymentMethod) and a registry of things that implement it. New behaviour arrives as new code beside the old, and the tested core doesn’t move.

Don’t build the seam too early#

Two cases in a switch are fine. Introduce the interface when the third or fourth case is clearly coming, or when the cases live in different teams’ hands. Building plug-in systems for things that never grow is exactly what You aren’t gonna need it warns about.

Check yourself

What does “closed for modification” mean?