Strategy

Policy

Escrito por Darjus Kazakevic · revisado el

Swap the algorithm, not the if-statement.

Some rules vary: how shipping is priced, how a discount applies, how a file is parsed. They start as one if, then grow into a switch that appears in two places and must stay in sync. The variation is real, but a conditional is a bad place to keep it.

Strategy puts each variant behind one interface and picks one at runtime. Adding a variant becomes adding one entry. In TypeScript the interface is often just a function type, and the set of strategies is a map of functions, with no class hierarchy.

En esencia — Put each variant of an algorithm behind one interface and choose one at runtime, so adding a variant is a new entry, not a new branch.

Cuándo recurrir a él

Recurre a él cuando

  • The same switch on a mode appears in two places that must agree
  • New variants keep arriving: carriers, tax rules, file formats
  • You want to test each variant on its own

Reconsidéralo cuando

  • Two stable branches that have not changed in a year
  • Variants need different inputs, so one signature would be a lie
  • Only one variant exists today, and no second one is planned

Conceptos clave

Strategy interface
The one signature every variant shares, such as (parcel) => price. If variants need different inputs, they are not one strategy.
Concrete strategy
One implementation of that interface: Royal Mail pricing, DPD pricing. Each one is small, lives on its own, and can be tested alone.
Context and registry
The code that picks a strategy and calls it. Usually a lookup by key, chosen from config or user input. The caller does not know the list of variants.
In modern TypeScript
A function is the simplest strategy, and Record<Key, Fn> is the registry. A variant with settings is a closure. Use a class only for variants with state or several methods.

Reglas de diseño

Callers must never learn the list
Adding a variant should mean one new function and one registry line, with no caller reopened. If callers still branch on which strategy they got, the conditional has only moved.
Start with a function, not a class
type Rate = (p: Parcel) => number and a Record of them is the whole pattern. Use classes only when a variant carries state or several related methods.
Type the key so a missing variant fails
Record<Carrier, Rate>, with Carrier as a union type, makes the compiler reject a registry that forgets a carrier. A Map<string, Rate> only fails at runtime, in production.

Errores habituales

  • Callers that still check which strategy they got (if rate === dpd). The conditional has only moved.
  • An interface with optional parameters that only some variants use. They were never one strategy.
  • A class hierarchy (AbstractRateStrategy, BaseRate…) for what is three small functions.
  • Choosing the variant in several places, so the choices disagree. Choose once, at the edge, and pass it in.