Strategy: interchangeable algorithms

  • Lesson 18 of 32
  • 10 min
  • Beginner
  • 12 steps

A shipping calculation with one `if` per type grows every time a new type arrives. You will move each algorithm into its own piece, behind one contract, so the code that uses it only has to delegate.

Per-type branches in quote()
0
Strategy in use
express
Checkoutquote()sort()passportquote()Standardstandarda - bLocalStrategyStandardShippingcontractcompareFncontractShippingExpressexpressb - aOpenIDConnectExpressFreefreeFreequote("express", 3)one if per typequote() with one if per typefunction quote(kind: string, kg: number) {if (kind === "standard") return 5 + kg;if (kind === "express") return 12 + kg * 2;throw new Error(kind);}editing quote() againFree shipping arrivesfunction quote(kind: string, kg: number) {if (kind === "standard") return 5 + kg;if (kind === "express") return 12 + kg * 2;+if (kind === "free") return 0;throw new Error(kind);}the contract5 + kg12 + kg × 2One contract, one class per algorithminterface Shipping {▸cost(kg: number): number;}class Express implements Shipping {cost(kg: number) {return 12 + kg * 2;}}no if: it delegates5 + 3 = 8quote() receives the strategyfunction quote(s: Shipping, kg: number) {▸return s.cost(kg);}quote(new Standard(), 3); // 812 + 3 × 2 = 18the same quote()Another strategy, the same quote()quote(new Standard(), 3); // 8▸quote(new Express(), 3); // 18new classunchangedFree shipping: only an addition+class Free implements Shipping {+cost() { return 0; }+}quote(new Free(), 3); // 0a functiona function typeNo classes: functions▸type Shipping = (kg: number) => number;const standard: Shipping =(kg) => 5 + kg;const express: Shipping =(kg) => 12 + kg * 2;const free: Shipping = () => 0;the user picked expresslooks it up in the mapThe choice, in one placeconst strategies: Record<string, Shipping>= { standard, express, free };function quote(kind: string, kg: number) {▸const s = strategies[kind];if (!s) throw new Error(kind);return s(kg);}negative, 0 or positivesorts in placeArray.prototype.sort takes the strategyconst p = [18, 0, 8];▸p.sort((a, b) => a - b); // [0, 8, 18]p.sort((a, b) => b - a); // [18, 8, 0]username and passwordanother packagePassport: install, configure, register// npm install passport-local▸passport.use(new LocalStrategy(verify));passport.authenticate("local");what if it needs the total?2 fixed branches: keep the ifWhen not, and what it costs2 branches that never growkeep the ifvery different inputsthe contract liesone piece per algorithmmore files to reada strategy mapmust be kept in syncreceives and delegatesStrategy in one tableproblemone if per type that keeps growingsolutionone contract, one piece per algorithmthe callerdelegates without asking the typein JS or TSa function is enoughskip itwith 2 fixed branches
  • request
  • response

Step 1 of 12

Problem

One if per shipping type

Your shop computes shipping with quote(kind, kg). There are two types: standard costs 5 plus 1 per kilo and express, 12 plus 2 per kilo. The function tells them apart with one if per type.

With two branches it still reads fine. The trouble starts when the business asks for a new type, because each one is one more branch inside the same function.

What changed

  • quote() with two branches

Step 2 of 12

Problem

Every new type opens the same function

Free shipping arrives and you open quote() again to add its branch. Tomorrow it will be in-store pickup, and the same again.

Every change touches code that already worked: you can break standard while adding free, and the function's tests grow with every branch. That if per type grows every sprint.

What changed

  • free branch
  • quote(), edited again

Step 3 of 12

Concept

One contract, one piece per algorithm

First define what every shipping type has in common: a Shipping contract with a cost(kg) method. Then each rate lives in its own class that fulfils it: Standard, Express.

That is a family of interchangeable algorithms, the idea Gamma, Helm, Johnson and Vlissides use to present Strategy in their 1994 book. Each algorithm is read and tested on its own.

What changed

  • interface Shipping
  • Standard and Express

Step 4 of 12

Solution

quote() receives the strategy and delegates

Now quote() receives a Shipping and asks it for s.cost(kg). It does not ask which type it is: it delegates to the object it was given.

With a 3 kg order and Standard, the price is 5 + 3 = 8. The per-type branches inside quote() went from 2 to 0.

What changed

  • the per-type ifs
  • s.cost(kg)

Step 5 of 12

Technique

Another strategy, the same code

If the user picks express, you pass new Express() instead of new Standard(). The same quote() returns 12 + 3 × 2 = 18.

The choice happens at runtime: depending on what the user ticks, the country or an experiment, one piece or another goes in, and the code that uses it does not change.

What changed

  • Standard → Express

Step 6 of 12

Solution

A new shipping type without touching quote()

Free shipping is no longer a branch: it is a new class, Free, that fulfils Shipping and returns 0. quote() stays closed.

The code is open for extension and closed for modification: you add an algorithm by writing a new one, without editing the ones that already work or their tests.

What changed

  • class Free
  • quote(), unchanged

Step 7 of 12

Technique

A function is enough

Strategy does not require one class per algorithm. In languages where functions are values, such as JavaScript or TypeScript, the strategy can be a function: the contract is the type (kg: number) => number.

Peter Norvig pointed this out in 1996, in his talk on patterns in dynamic languages: in such a language, 16 of the book's 23 patterns become invisible or simpler. If your strategy is a single method with no state, start with a function.

What changed

  • the classes
  • type Shipping as a function

Step 8 of 12

Technique

The decision does not vanish: it moves

Strategy does not remove the choice: something has to turn the text "express" into the right strategy. The difference is that it happens once, in one place, for example a map from name to function.

quote() looks it up in the map, fails if the type does not exist and delegates. A new shipping type is one more function and one more map entry, not another branch in every place that computes prices.

What changed

  • strategies map
  • quote(kind, kg) looks up and delegates

Step 9 of 12

Concept

You already use it: `Array.prototype.sort`

sort knows how to sort, but not what «smaller» means to you: you pass that in as a compare function. If it returns a negative number, a goes first; if positive, b goes first; with 0 they keep their order.

You change the order by changing only the function: a - b sorts from low to high and b - a, the other way. sort changes the array in place and, since ES2019, it is stable: ties keep their original order.

What changed

  • quote() → sort()
  • strategies → compare functions

Step 10 of 12

Concept

Passport: one strategy per way to log in

Passport.js, an authentication library for Node.js, calls each login mechanism a strategy: passport-local for username and password, passport-openidconnect for OpenID Connect, among others.

Each one is a package you install, configure and register with passport.use(). Then passport.authenticate("local") uses the one registered under that name, and your route does not know how the credential is checked.

What changed

  • quote() → passport
  • strategies → login packages

Step 11 of 12

Trade-off

When an if is enough

If you have two branches that will not grow, keep the if: a contract and two pieces are more files to read for no gain. And if each algorithm needs very different inputs, for example free shipping that depends on the cart total and not on the weight, the shared contract lies.

The pattern has a cost too: the logic is spread over several pieces and the strategy map has to be kept up to date. It pays off when the family grows or when you want to test each algorithm on its own.

Step 12 of 12

Summary

Choose once, always delegate

When an if per type grows with every new case, move each algorithm into a piece with the same contract and let the code that uses them receive one and delegate. Adding a case means writing a new piece, without touching the others.

In JavaScript or TypeScript a function is often enough; you see it in sort and Passport. The choice does not vanish: it happens once, at the edge. With two fixed branches, keep the if.

You will learn

  • Spot the `if` per type that you edit for every new case.
  • Move each algorithm into a piece with the same contract and delegate to it.
  • Add or swap an algorithm without touching the code that uses it.
  • Write the strategy as a function and recognise it in `sort` and Passport.
  • Know when an `if` is enough and what the pattern costs.