Pattern 02/22 · Behavioral

Strategy

Pull an algorithm that keeps changing out into separate objects (the "strategies"), and let the object that uses it pick one at runtime instead of hard-coding the choice with if/else.

Behavioral●○○12 min read8 stepsalso known as: Policy, Algorithm
algorithmif elsepluginbehavioraldependency injectionfunction

01 — It starts with code that is breaking

Problem

You're writing the shipping fee calculation for an online shop. Standard orders: 30,000 VND. Express: 30,000 + 10,000/kg. Orders of 500k and up: free. VIP customers: 50% off. You write the first version in 2 minutes:

Then product adds a second type, a third, a fourth. calculateShipping() balloons into an endless if/else tree. Every time marketing changes a number, you edit that exact function, and every edit risks breaking a branch you weren't thinking about.

Worse: you can't test this function in isolation. To test "express for a 3kg order" you have to build a whole Order object and call a giant function that also contains the logic for every other type. And when two teams edit two different branches of the same if/else, merge conflicts are a daily event.

The real problem isn't if/else. It's that several different ways of doing the same thing are crammed into one place, and the code calling it has to know every possibility.

02 — The idea, before touching code

Solution

The strategy is: each way of calculating the fee becomes its own object, and they all share the same "contract" (interface). The code that needs a fee just calls that contract without knowing what's inside.

The part that doesn't change (the checkout process: get address → calculate fee → create order) stays in the context class. The part that keeps changing (the fee formula) lives in strategy classes, one class per file, one responsibility per file. Need a new fee type? Add a new file. Don't touch the old code.

In TypeScript/JavaScript, "an object with the same interface" is often just a function. So the most common form of Strategy in JS needs no interface at all: it's a function passed in as an argument. You've used Strategy a hundred times: array.sort((a, b) => a.price - b.price).

03 — Doing it for real, one code fragment per step

Step by step

1

Write the "bad smell" version first

This is the code everyone writes the first time. Don't be afraid of it; just identify exactly where it's going to grow.

tscheckout-v1.ts
type ShippingType = 'standard' | 'express' | 'free' | 'vip'

class Checkout {
  calculateShipping(order: { total: number, weightKg: number }, type: ShippingType): number {
    if (type === 'standard') {
      return 30_000
    }
    else if (type === 'express') {
      return 30_000 + order.weightKg * 10_000
    }
    else if (type === 'free') {
      return order.total >= 500_000 ? 0 : 20_000
    }
    else if (type === 'vip') {
      return order.total * 0.5 * 0.5 // 50% off, still charges the standard fee
    }
    throw new Error('unknown shipping type: ' + type)
  }
}
All shipping knowledge lives in one function. The 5th else if will arrive very soon.
Key pointThe Strategy signal: a function with many if/else branches where each branch differs only in how it computes, not in what it returns.
2

Separate what changes from what doesn't

Before writing code, grab a pen and underline. In the checkout process, the part that doesn't change: receive the order, validate the address, calculate the fee, save the order, send the email. The part that changes: in each place it's just one line, the line that calculates the fee.

So we only need to pull out one thing: "calculate the fee from an order". Its contract: input Order, output number. Write that contract down as a type.

tsshipping-strategy.ts
export type Order = { id: string, total: number, weightKg: number }

/** The "contract": every fee calculation must match this shape. */
export interface ShippingStrategy {
  readonly name: string
  fee(order: Order): number
}
This interface is the pattern's entire "abstraction". It's cheap, and it stays put while every formula changes.
Key pointStrategy doesn't abstract "a whole class", it abstracts one specific behavior. The more specific it is, the easier the interface is to get right.
3

Turn each algorithm into a strategy

Each old if/else branch becomes an object. One object per file (or a small group in one file if they're simple). No object knows about the others.

tsstrategies.ts
import type { Order, ShippingStrategy } from './shipping-strategy'

export const standardShipping: ShippingStrategy = {
  name: 'standard',
  fee: () => 30_000,
}

export const expressShipping: ShippingStrategy = {
  name: 'express',
  fee: (o: Order) => 30_000 + Math.round(o.weightKg) * 10_000,
}

export const freeOver500k: ShippingStrategy = {
  name: 'free-over-500k',
  fee: (o: Order) => (o.total >= 500_000 ? 0 : 20_000),
}

export const vipDiscount: ShippingStrategy = {
  name: 'vip',
  fee: (o: Order) => Math.round(standardShipping.fee(o) * 0.5),
}
Note: each strategy can be tested on its own as a plain function, without building a Checkout.
Key pointTesting a strategy = calling a function. No mocks, no DB, no "40 lines of fixture setup".
4

Let the context receive the strategy from outside

Checkout is now just the context: it runs the process and delegates the fee calculation to a strategy that was passed in. It doesn't new any strategy and doesn't compare type === ... anywhere.

tscheckout-v2.ts
import type { Order, ShippingStrategy } from './shipping-strategy'

export class Checkout {
  constructor(private strategy: ShippingStrategy) {}

  total(order: Order): number {
    return order.total + this.strategy.fee(order)
  }

  report(order: Order): void {
    const fee = this.strategy.fee(order)
    console.log(`${order.id} · ${this.strategy.name}: fee ${fee} VND, total ${order.total + fee} VND`)
  }
}
No more if. No more throw new Error("unknown type"): TypeScript catches it right at the call site.
Key pointThe context depends on the interface, not on the implementation. That's Dependency Injection, and Strategy is its most classic form.
5

Pick the strategy at runtime (not at write time)

The customer switches from "standard" to "express" right on the checkout page? Swap the strategy. That's the whole power of the pattern: the same object, different behavior over time.

tsdemo.ts
import { Checkout } from './checkout-v2'
import { standardShipping, expressShipping, freeOver500k } from './strategies'

const order: Order = { id: 'ORD-01', total: 640_000, weightKg: 3 }

const checkout = new Checkout(standardShipping)
checkout.report(order)

checkout.setStrategy(expressShipping) // customer clicks "Express"
checkout.report(order)

checkout.setStrategy(freeOver500k)   // has a discount code
checkout.report(order)
console
ORD-01 · standard: fee 30000 VND, total 670000 VND
ORD-01 · express: fee 60000 VND, total 700000 VND
ORD-01 · free-over-500k: fee 0 VND, total 640000 VND
6

Replace if/else with a registry when strategies come from data

In real life, the strategy usually comes from the DB, a query string, an admin config: ?shipping=express. At that point you don't import each one and if over them; you look it up in a map. The if/else disappears completely.

tsregistry.ts
import type { ShippingStrategy } from './shipping-strategy'
import { standardShipping, expressShipping, freeOver500k, vipDiscount } from './strategies'

export const shippingRegistry: Record<string, ShippingStrategy> = {
  'standard': standardShipping,
  'express': expressShipping,
  'free-over-500k': freeOver500k,
  'vip': vipDiscount,
}

export function pickShipping(key: string): ShippingStrategy {
  const found = shippingRegistry[key]
  if (!found) throw new Error(`No shipping strategy "${key}"`)
  return found
}

// router/server: const strategy = pickShipping(query.shipping ?? 'standard')
New fee type = 1 map entry + 1 file. No existing file gets edited. That's the Open/Closed Principle in the flesh.
7

Plain JS version: a strategy is just a function

If the strategy holds no state, an { name, fee() } object is unnecessary ceremony. In TS, functions are first-class, so the contract shrinks to a single type:

tsfunction-version.ts
export type FeeFn = (order: Order) => number

export const calculateTotal = (order: Order, fee: FeeFn = o => (o.total >= 500_000 ? 0 : 30_000)) =>
  order.total + fee(order)

calculateTotal({ id: 'ORD-02', total: 120_000, weightKg: 1 })              // 150000
calculateTotal({ id: 'ORD-02', total: 120_000, weightKg: 1 }, () => 0)     // 120000

// and this is the Strategy you've been writing all year:
[12, 4, 9].sort((a, b) => a - b)          // [4, 9, 12]
[12, 4, 9].sort((a, b) => b - a)          // [12, 9, 4]  <- same sort(), different strategy
Key pointUse an interface/class when the strategy has state or needs several methods. Use a function when it's just a calculation. Don't add ceremony.
8

Check again: is it closed, is it open

The final test of this refactor: add a new fee type without editing any existing file. If you have to touch Checkout or an old strategy, something somewhere still "knows" too much.

tsnight-shift.ts
// A NEW file. The only one. Nothing else changes.
import type { ShippingStrategy } from './shipping-strategy'

export const nightShift: ShippingStrategy = {
  name: 'night-shift',
  fee: (o) => (o.weightKg <= 2 ? 15_000 : 40_000),
}

// + 1 line in the registry: 'night-shift': nightShift
If adding a feature costs "add a file" rather than "edit old files", you are closed for modification and open for extension.

04 — Who talks to whom

Structure

  • StrategyThe shared contract for every algorithm: `fee(order): number`.
  • ConcreteStrategyOne specific calculation: standard, express, vip... They know nothing about each other.
  • ContextRuns the shared process, holds a Strategy reference, calls `strategy.fee()` at the right moment.
  • ClientPicks and (if needed) swaps the Context's strategy, usually based on input/user/config.
            ┌────────────────┐
   Client   │  picks/swaps   │
  ─────────►│  the strategy  │
            └───────┬────────┘
                    │ setStrategy(s)
                    ▼
   ┌──────────────────────────────┐
   │ Context (Checkout)           │  only runs the shared process
   │  - strategy: ShippingStrategy│
   │  + total(order)  ──► strategy.fee(order)
   └──────────────┬───────────────┘
                  │ uses the contract, not the implementation
        ┌─────────┼──────────────┐
        ▼         ▼              ▼
   ┌─────────┐┌─────────┐  ┌──────────┐
   │standard ││ express │  │   vip    │   ... add new files
   │30,000   ││+10k/kg  │  │ 50% fee  │      as needed
   └─────────┘└─────────┘  └──────────┘

05 — Edit freely, run it right here

Try it: one Checkout, three strategies

tsdemo.ts
type Order = { id: string, total: number, weightKg: number }

interface ShippingStrategy {
  readonly name: string
  fee(order: Order): number
}

const standard: ShippingStrategy = {
  name: 'standard',
  fee: () => 30_000,
}

const express: ShippingStrategy = {
  name: 'express',
  fee: o => 30_000 + Math.round(o.weightKg) * 10_000,
}

const freeOver500k: ShippingStrategy = {
  name: 'free-over-500k',
  fee: o => (o.total >= 500_000 ? 0 : 20_000),
}

// Registry: new fee type = add 1 line, Checkout stays untouched
const registry: Record<string, ShippingStrategy> = {
  'standard': standard,
  'express': express,
  'free-over-500k': freeOver500k,
}

class Checkout {
  constructor(private strategy: ShippingStrategy) {}

  setStrategy(s: ShippingStrategy) {
    this.strategy = s
  }

  report(order: Order) {
    const fee = this.strategy.fee(order)
    console.log(`${order.id} · ${this.strategy.name}: fee ${fee} VND, total ${order.total + fee} VND`)
  }
}

const order: Order = { id: 'ORD-01', total: 640_000, weightKg: 3 }
const checkout = new Checkout(registry['standard'])
checkout.report(order)
checkout.setStrategy(registry['express'])
checkout.report(order)
checkout.setStrategy(registry['free-over-500k'])
checkout.report(order)
console
ORD-01 · standard: fee 30000 VND, total 670000 VND
ORD-01 · express: fee 60000 VND, total 700000 VND
ORD-01 · free-over-500k: fee 0 VND, total 640000 VND

The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.

06 — Honest about the cost

When to use it, when not to

Use it when

  • Several classes differ in exactly one behavior (fee calculation, sorting, validation, rendering, export format).
  • You need to change an object's behavior while it's running without rebuilding it.
  • A function contains a big if/else or switch where each branch is just a different formula.
  • You want algorithms tested in isolation, or you want users/admins to pick the algorithm via config.
  • You need several levels of detail for the same logic: a fast version for previews, an exact one for the end-of-day report.

Don't use it when

  • Over-engineering. Two if/else branches and you're sure they won't move for 3 years? Don't build 5 files + 1 interface. Strategy pays off once there are ≥ 3 branches and the number is still growing.
  • This pattern increases the number of classes. A 3-file module turns into 12 files; compensate by keeping them in one folder with consistent naming.
  • The client has to know how the strategies differ in order to pick one. If picking is complex business logic, move that decision into its own function/service; don't let the UI pick on its own.
  • In JS, closures make it easy for a strategy to become "a function that quietly holds state". Keep strategies pure if you can; if not, name them so it's obvious.
  • Don't stuff I/O (calling an API for exchange rates) into a fee strategy and then treat it as a pure function. You'll cry when you test it.

07 — You have met it already, just not by name

In real code

array.sort(comparator)

The comparator is the sorting strategy. Same sort engine, completely different behavior depending on the function you pass in. This is the purest Strategy that exists in JS.

addEventListener(type, handler)

The event system is Strategy at scale: a "context" (the DOM/event loop) calls behavior supplied by someone else, without needing to know what the handler does.

Intl.NumberFormat / Intl.Collator

You pass a locale (a "strategy config") and the same format() function produces different output depending on the culture.

Service layer in Nuxt/Node

exportPayment(order, gateway), sendNotification(msg, channel) with a { email, sms, webpush } map: a Strategy registry. Adding a new channel doesn't touch old code.

08 — Try it yourself

Exercise

Rewrite `renderReport(rows, format)`, which currently has `if (format === "csv") ... else if (format === "json") ... else if (format === "md") ...`, as a Strategy, and make it possible to add an `html` format without editing `renderReport`.

Hints, open them one at a time:

  1. What's the contract? What are the input/output of a "format"?
  2. One object per format: { name, render(rows): string }.
  3. Use Record<string, RenderStrategy> to look up by format, and fall back to csv if it's not found.

Declare an interface RenderStrategy { name, render(rows) }, turn each branch into an object, and replace the if/else tree with registry[format] ?? registry.csv. Adding html = one new object + one registry line.

tsexercise.ts
type Row = Record<string, string | number>
interface RenderStrategy { name: string, render(rows: Row[]): string }

const csv: RenderStrategy = {
  name: 'csv',
  render: rows => {
    const head = Object.keys(rows[0] ?? {}).join(',')
    return [head, ...rows.map(r => Object.values(r).join(','))].join('\n')
  },
}

const json: RenderStrategy = { name: 'json', render: rows => JSON.stringify(rows) }

const html: RenderStrategy = { // <- NEW file/format, renderReport untouched
  name: 'html',
  render: rows => `<table><tbody>${rows.map(r => `<tr>${Object.values(r).map(v => `<td>${v}</td>`).join('')}</tr>`).join('')}</tbody></table>`,
}

const registry: Record<string, RenderStrategy> = { csv, json, html }

const renderReport = (rows: Row[], format: string) =>
  (registry[format] ?? registry.csv).render(rows)

console.log(renderReport([{ a: 1, b: 2 }], 'html'))

09 — Read them in pairs to see the essence

Related patterns

  • StateIdentical code: Strategy says "pick an algorithm", State says "the state decides the behavior and transitions itself". Read this pair to see that intent matters more than structure.
  • CommandStrategy parameterizes *how to do it*; Command packages *what to do* into an object you can queue, undo and log.
  • Template MethodSame goal (swap one step of an algorithm), but Template Method does it with inheritance and Strategy with composition. Strategy is more flexible because it can be swapped at runtime.
  • DecoratorBoth use composition. Decorator *wraps* extra behavior around, Strategy *replaces* behavior.