skipnothing/Design Patterns

Strategy

A process(type, amount) method has gained a fresh case every release for six months. Card, PayPal, crypto, gift card, store credit, BNPL, each new payment type adds a branch and pushes the file past 200 lines.

  • ▸A process method gains a fresh case every payment type, every release edits the same file.
  • ▸Move the algorithm out of the class, and the class is byte-identical whether it serves 3 variants or 30.
  • ▸Array.sort((a,b) => a - b), sorted(key=…), Comparator, three stdlibs spell the same idea three ways.
01

The growing switch

Open the file every team complains about. It usually starts like this:

class PaymentProcessor {
  process(type, amount) {
    switch (type) {
      case 'credit':
        // 12 lines: validate card, talk to gateway, log
        return chargeCredit(amount);
      case 'paypal':
        // 10 lines: redirect URL, polling, callback
        return chargePaypal(amount);
      case 'crypto':
        // 18 lines: pick chain, get address, watch confirmations
        return chargeCrypto(amount);
    }
  }
}

The shape isn't the problem, switch, an if-else ladder, a dict mapping strings to functions, all read the same. The problem is the *trajectory*. Every new payment type adds a branch. Every change to credit-card handling touches a method that also handles PayPal and crypto. Run git blame and the same file shows up in every release.

The class doesn't have one job; it has six, joined by a tag. Every variant lives inside one method body, and the method body owns nothing, it's a router that forwards based on a string. The variants don't collide today. They will when the seventh appears.

THE SMELL THAT GROWS

Keep going, sign up to unlock the rest

4 more parts in this topic, plus 18+ more topics in Design Patterns.

Sign up, it's freeSee the full Design Patterns
Behavioral Patterns0/6#1 Observer
#3 State