On Monday, Leo, the organizer of the spring show, sent Maya three requests. Buyers wanted to pay with a phone wallet. Leo wanted seats held for his regular guests, who pay at the door. He also wanted every failed refund retried and logged.
Maya searched the code. She found if (method === "card") in four files and status checks in six.
“Can you add all three?” Leo wrote.
“Yes,” Maya wrote back. “But first I want each change in one place.”
Maya, Leo and TinyTickets are invented, and so are the numbers in their story.
Each request needs code that behaves differently from case to case, without edits to the code around it. This module teaches three patterns for that, Strategy, State and Command, and adds a short entry on Template Method. Each pattern gets a working example, a test, and a rule for when it costs more than it saves.
After this module, you can:
- replace an
ifchain over payment providers with a Strategy, and testcheckoutwith a fake provider - move status checks that are spread across handlers into one State object per status
- turn admin actions into Commands, plain data that you can log, keep and run again
- choose between these patterns, Template Method and a plain
switch, and say when none is needed
Every example runs on its own with npx tsx file.ts, from a folder set up as in Module 1. The payment, mail and seat services here are fakes that print a line instead of calling a real service.
Strategy: let the caller choose the payment provider
Three payment methods and one growing if chain
TinyTickets takes card payments. Leo wants a phone wallet too, and the wallet app refuses any single payment over $100. Maya added the wallet inside checkout. Save it as checkout-before.ts:
type PaymentMethod = "card" | "wallet";
type PaymentResult =
| { status: "paid"; chargeId: string }
| { status: "declined"; reason: string };
async function checkout(method: PaymentMethod, quantity: number): Promise<string> {
const totalCents = 1200 * quantity + (quantity >= 4 ? 0 : 150);
let result: PaymentResult;
if (method === "card") {
console.log(`[card] charged ${totalCents} cents`);
result = { status: "paid", chargeId: "card_1" };
} else if (totalCents > 10000) {
// the wallet app refuses payments over $100
result = { status: "declined", reason: "over the wallet limit" };
} else {
console.log(`[wallet] charged ${totalCents} cents`);
result = { status: "paid", chargeId: "wallet_1" };
}
if (result.status === "declined") return `declined: ${result.reason}`;
return `paid with ${result.chargeId}`;
}
console.log(await checkout("card", 2));
console.log(await checkout("wallet", 2));
console.log(await checkout("wallet", 9));
Output:
[card] charged 2550 cents
paid with card_1
[wallet] charged 2550 cents
paid with wallet_1
declined: over the wallet limit
The code works. But Leo asks for bank transfers next, so Maya must add a third branch in the middle of checkout. In the real code, the same method checks also sit in the refund route, the receipt text and the admin report. So “bank” means four edits in four files.
Testing is harder too. To check what checkout answers when a card is declined, you need a card that declines. The card branch never declines, so a test can’t reach that line without a mocking tool, a library that swaps real code for a fake during a test.
Pause and predict: which lines of
checkoutchange when a payment method is added, and which never change? Where could the changing lines live, so thatcheckoutdoesn’t know which method it uses?
The idea: one interface, many ways to do one step
Strategy comes from the GoF book, the 1994 book that Module 1 introduced. It’s a behavioral pattern, one that decides how objects share work. Strategy puts each way of doing one step behind the same interface, and the caller hands the code the one to use. Here the step is “charge the buyer”, and each way of doing it is a payment provider.
At a shop counter, the cashier adds up your items the same way every time. Then the cashier asks “card or phone?” and hands you the matching reader. In the code, checkout always computes the total and charges once, and only the provider it receives changes.
Figure 1 puts the counter next to the code. It also has the legend that every figure in this course uses.
At the shop counter In TinyTickets
(Cashier) [checkout]
asks "card or phone?" [checkout-main.ts] picks from [providers]
[card reader] [phone reader] [CardProvider] [WalletProvider]
Legend, the same in every module
(Name) a person
[name] a module, function or class
[name] (I) an interface: a shape that other code must fit
A --> B A calls B
A ..> B A implements B: A has the shape that interface B asks for
A ==> B A creates B (with "new" or a factory function)
NEW a part that the change added
~ await ~ the caller waits here; Node.js serves other work meanwhile
Figure 1: the cashier’s steps stay the same; only the reader in the buyer’s hand changes.
The fix: pass a provider to checkout
The step that changes moves into classes that share one interface. Save providers.ts:
// Fake payment providers. They print instead of calling a real service.
export type PaymentResult =
| { status: "paid"; chargeId: string }
| { status: "declined"; reason: string };
export interface PaymentProvider {
charge(amountCents: number): Promise<PaymentResult>;
}
export class CardProvider implements PaymentProvider {
async charge(amountCents: number): Promise<PaymentResult> {
console.log(`[card] charged ${amountCents} cents`);
return { status: "paid", chargeId: "card_1" };
}
}
export class WalletProvider implements PaymentProvider {
#limitCents: number;
constructor(limitCents: number) {
this.#limitCents = limitCents;
}
async charge(amountCents: number): Promise<PaymentResult> {
if (amountCents > this.#limitCents) {
return { status: "declined", reason: "over the wallet limit" };
}
console.log(`[wallet] charged ${amountCents} cents`);
return { status: "paid", chargeId: "wallet_1" };
}
}
A field whose name starts with # is a private field, which no code outside the class can read. So the wallet limit is now a setting of WalletProvider, not a number inside checkout. The steps that stay the same go into checkout.ts:
import type { PaymentProvider } from "./providers.ts";
// What stays the same: the total, one charge, the answer
export async function checkout(provider: PaymentProvider, quantity: number): Promise<string> {
const totalCents = 1200 * quantity + (quantity >= 4 ? 0 : 150);
const result = await provider.charge(totalCents);
if (result.status === "declined") return `declined: ${result.reason}`;
return `paid with ${result.chargeId}`;
}
The choice happens in one place, checkout-main.ts:
import { checkout } from "./checkout.ts";
import { CardProvider, WalletProvider, type PaymentProvider } from "./providers.ts";
type PaymentMethod = "card" | "wallet";
// What changes: one provider per payment method, created once
const providers: Record<PaymentMethod, PaymentProvider> = {
card: new CardProvider(),
wallet: new WalletProvider(10000),
};
console.log(await checkout(providers["card"], 2));
console.log(await checkout(providers["wallet"], 2));
console.log(await checkout(providers["wallet"], 9));
npx tsx checkout-main.ts prints the same five lines as checkout-before.ts. Figure 2 shows the structure before and after.
Before
[checkout] if card ... else if over limit ... else wallet ...
After
[checkout-main.ts] ==> [CardProvider] [WalletProvider] NEW
[CardProvider] ..> [PaymentProvider] (I) NEW
[WalletProvider] ..> [PaymentProvider] (I)
[checkout-main.ts] --> [checkout] --> [PaymentProvider] (I)
Figure 2: checkout now calls one interface; the file that starts the app decides which provider fills it.
In a real route, the buyer sends the method in the request body. Check that the value is "card" or "wallet" before you use it as a key, as Module 1 checked the body fields. Then providers[method] picks the strategy while the app runs.
Rule: the code that stays the same takes the varying step as a parameter, and one place creates the choices and picks one.
Prove it with a test
The test passes in a provider that always declines and records what it was asked to charge. Save checkout.test.ts:
import { test } from "node:test";
import assert from "node:assert/strict";
import { checkout } from "./checkout.ts";
import type { PaymentProvider } from "./providers.ts";
test("checkout charges the total and reports a decline", async () => {
const charged: number[] = [];
const decliningProvider: PaymentProvider = {
async charge(amountCents) {
charged.push(amountCents);
return { status: "declined", reason: "card expired" };
},
};
const answer = await checkout(decliningProvider, 2);
assert.deepEqual(charged, [2550]);
assert.equal(answer, "declined: card expired");
});
Run it with npx tsx --test checkout.test.ts:
✔ checkout charges the total and reports a decline (0.672791ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0
The fake is a plain object. It fits PaymentProvider because TypeScript compares shapes, not class names (structural typing, from Module 1). The “before” version had no place for a fake, because the card branch never declined.
The next change: bank transfers
Leo asks for bank transfers. Save bank-transfer-provider.ts:
import type { PaymentProvider, PaymentResult } from "./providers.ts";
export class BankTransferProvider implements PaymentProvider {
async charge(amountCents: number): Promise<PaymentResult> {
console.log(`[bank] transfer of ${amountCents} cents requested`);
return { status: "paid", chargeId: "bank_1" };
}
}
Then add one import, one word and two lines to checkout-main.ts. This excerpt shows only the changed lines, and the rest of the file stays the same:
import { BankTransferProvider } from "./bank-transfer-provider.ts";
type PaymentMethod = "card" | "wallet" | "bank"; // NEW: "bank"
bank: new BankTransferProvider(), // NEW
console.log(await checkout(providers["bank"], 4)); // NEW
The output gains two lines:
[bank] transfer of 4800 cents requested
paid with bank_1
checkout.ts and its test didn’t change. If you add "bank" to the union and forget the provider, tsc reports that the property bank is missing.
When Strategy is worth it
Use Strategy when:
- an
iforswitchover the same “kind” value (method,provider,channel) appears in more than one place - each branch needs its own setting or client, like the wallet limit or an API key
- a test needs to replace one branch with a fake
Skip it when the branches are two or three short lines in one function and haven’t changed in months. There, a switch on a union is enough, with the never check from Module 1 that makes tsc fail when a case is missing.
Strategy costs an interface, a class or file per provider, and a place that creates them. It also hides which code runs. “Go to definition” on provider.charge lands on the interface, so you must read checkout-main.ts to learn which provider runs.
Exercise: free tickets for the guest list
Leo gives some tickets away to his guest list. Write a provider for those orders that charges nothing and answers paid with guest-list. Which files change?
Answer
A plain object is enough, because the provider needs no setting. Save free.ts:
import { checkout } from "./checkout.ts";
import type { PaymentProvider } from "./providers.ts";
// Leo's guest list: nothing to charge
const guestList: PaymentProvider = {
async charge() {
return { status: "paid", chargeId: "guest-list" };
},
};
console.log(await checkout(guestList, 2));
It prints paid with guest-list. This charge takes no parameter, and it still fits PaymentProvider, because TypeScript allows a function with fewer parameters where more are passed. Only the file that picks the provider changes, and checkout.ts stays as it is.
State: one object per order status
Status checks spread across handlers
An order in TinyTickets moves through four statuses: pending, paid, cancelled and refunded. Each action is allowed only in some of them, and three handlers check the status, each in its own file.
One of those handlers answers a webhook. A webhook is an HTTP request that a provider sends to your server when something happens, and the payment webhook calls markPaid. Save types.ts, which later files share:
export type OrderStatus = "pending" | "paid" | "cancelled" | "refunded";
export interface Order {
id: string;
showId: string;
buyerEmail: string;
quantity: number;
totalCents: number;
status: OrderStatus;
}
Then save order-before.ts, which puts the three handlers in one file to keep the example short:
import type { Order } from "./types.ts";
// The payment webhook calls this when the money arrives
async function markPaid(order: Order): Promise<Order> {
if (order.status !== "pending") throw new Error(`cannot pay a ${order.status} order`);
console.log(`[mail] tickets for order ${order.id} sent to ${order.buyerEmail}`);
return { ...order, status: "paid" };
}
// The buyer's "cancel" button and the 15-minute hold timer call this
async function cancelOrder(order: Order): Promise<Order> {
if (order.status !== "pending") throw new Error(`cannot cancel a ${order.status} order`);
console.log(`[seats] released ${order.quantity} seats for ${order.showId}`);
return { ...order, status: "cancelled" };
}
// Leo's admin page calls this
async function refundOrder(order: Order): Promise<Order> {
if (order.status !== "paid") throw new Error(`cannot refund a ${order.status} order`);
console.log(`[card] refunded ${order.totalCents} cents`);
console.log(`[seats] released ${order.quantity} seats for ${order.showId}`);
return { ...order, status: "refunded" };
}
let order: Order = { id: "o1", showId: "spring", buyerEmail: "ana@example.com",
quantity: 2, totalCents: 2550, status: "pending" };
order = await markPaid(order);
order = await refundOrder(order);
console.log(`order ${order.id} is ${order.status}`);
try {
await cancelOrder(order);
} catch (err: unknown) {
if (err instanceof Error) console.log(err.message);
}
Output:
[mail] tickets for order o1 sent to ana@example.com
[card] refunded 2550 cents
[seats] released 2 seats for spring
order o1 is refunded
cannot cancel a refunded order
Now Leo’s second request arrives. He holds seats for his regular guests in a new status, reserved. A reserved order can be paid, and paying sends no ticket email, because guests pay at the door. A reserved order can also be cancelled.
Maya adds "reserved" to OrderStatus. She changes the check in markPaid to accept "reserved" and skip the email, and tsc passes. The next day Leo can’t cancel a guest’s seats, and the admin page shows cannot cancel a reserved order. The rule for reserved belonged in two handlers, and nothing pointed her to the second one.
Pause and predict: if you wanted every rule about one status in one place, how would you arrange the code? What could make
tscfail when a status has no answer for an action?
The idea: the status picks the behavior
State is another behavioral pattern from the GoF book. Each status gets its own object that answers every action, and the order hands each action to the object for its current status. A transition is a move from one status to another, such as pending to paid.
A vending machine has the same buttons all day. But what a button does depends on whether you’ve put a coin in. In the code, the order’s status picks which object answers pay, cancel or refund, as Figure 3 shows.
A vending machine An order
buttons: coin, choose, refund actions: pay, cancel, refund
"has a coin" or "no coin" order.status: pending, paid, ...
what the refund button does [orderStates.paid].refund
Figure 3: the same buttons give different answers, and the current status picks the answer.
The fix: orderStates and applyAction
The fix keeps the order as plain data and adds one object per status, with one function per action. The services the actions need come in as OrderEffects, so a test can pass a fake. Save order-states.ts:
import type { Order, OrderStatus } from "./types.ts";
export type OrderAction = "pay" | "cancel" | "refund";
// The outside work a state may need; a test passes a fake
export interface OrderEffects {
sendTickets(order: Order): Promise<void>;
releaseSeats(order: Order): Promise<void>;
refundMoney(order: Order): Promise<void>;
}
type Step = (order: Order, effects: OrderEffects) => Promise<OrderStatus>;
export type OrderState = Record<OrderAction, Step>;
const refuse = (action: OrderAction): Step => async (order) => {
throw new Error(`cannot ${action} a ${order.status} order`);
};
// One object per status. Each one answers every action.
export const orderStates: Record<OrderStatus, OrderState> = {
pending: {
pay: async (order, effects) => {
await effects.sendTickets(order);
return "paid";
},
cancel: async (order, effects) => {
await effects.releaseSeats(order);
return "cancelled";
},
refund: refuse("refund"),
},
paid: {
pay: refuse("pay"),
cancel: refuse("cancel"),
refund: async (order, effects) => {
await effects.refundMoney(order);
await effects.releaseSeats(order);
return "refunded";
},
},
cancelled: { pay: refuse("pay"), cancel: refuse("cancel"), refund: refuse("refund") },
refunded: { pay: refuse("pay"), cancel: refuse("cancel"), refund: refuse("refund") },
};
export async function applyAction(
order: Order,
action: OrderAction,
effects: OrderEffects,
): Promise<Order> {
const status = await orderStates[order.status][action](order, effects);
return { ...order, status };
}
refuse returns a step that always throws with the same message. Each step returns the next status, and applyAction returns a new order with it. Save order-main.ts, which runs the same story as before:
import type { Order } from "./types.ts";
import { applyAction, type OrderEffects } from "./order-states.ts";
const effects: OrderEffects = {
sendTickets: async (o) => console.log(`[mail] tickets for order ${o.id} sent to ${o.buyerEmail}`),
releaseSeats: async (o) => console.log(`[seats] released ${o.quantity} seats for ${o.showId}`),
refundMoney: async (o) => console.log(`[card] refunded ${o.totalCents} cents`),
};
let order: Order = { id: "o1", showId: "spring", buyerEmail: "ana@example.com",
quantity: 2, totalCents: 2550, status: "pending" };
order = await applyAction(order, "pay", effects);
order = await applyAction(order, "refund", effects);
console.log(`order ${order.id} is ${order.status}`);
try {
await applyAction(order, "cancel", effects);
} catch (err: unknown) {
if (err instanceof Error) console.log(err.message);
}
It prints the same five lines as order-before.ts. Figure 4 shows the structure before and after.
Before
[webhook] --> [markPaid] if status !== "pending" ...
[cancel btn] --> [cancelOrder] if status !== "pending" ...
[admin page] --> [refundOrder] if status !== "paid" ...
After
[webhook] [cancel btn] [admin page] --> [applyAction] NEW
[applyAction] --> [orderStates] --> [OrderEffects] (I) NEW
[orderStates] has pending, paid, cancelled, refunded
Figure 4: the status checks leave the three handlers and meet in orderStates.
The handlers keep their routes, and each one now calls applyAction with its action name. Figure 5 draws the statuses and the transitions between them. In this figure, a box is a status and a labeled line -- pay --> is a transition, not a call.
+---------+ -- pay --> +------+ -- refund --> +----------+
| pending | | paid | | refunded |
+---------+ +------+ +----------+
|
| -- cancel -->
v
+-----------+
| cancelled |
+-----------+
Any action not drawn here is refused: "cannot <action> a <status> order".
Figure 5: an order has four statuses and three transitions; everything else is refused.
Prove it with a test
The fake effects record what ran. Save order-states.test.ts:
import { test } from "node:test";
import assert from "node:assert/strict";
import type { Order } from "./types.ts";
import { applyAction, type OrderEffects } from "./order-states.ts";
const paidOrder: Order = { id: "o1", showId: "spring", buyerEmail: "ana@example.com",
quantity: 2, totalCents: 2550, status: "paid" };
function fakeEffects(calls: string[]): OrderEffects {
return {
sendTickets: async (o) => { calls.push(`tickets ${o.id}`); },
releaseSeats: async (o) => { calls.push(`seats ${o.quantity}`); },
refundMoney: async (o) => { calls.push(`refund ${o.totalCents}`); },
};
}
test("refunding a paid order returns the money, then frees the seats", async () => {
const calls: string[] = [];
const order = await applyAction(paidOrder, "refund", fakeEffects(calls));
assert.equal(order.status, "refunded");
assert.deepEqual(calls, ["refund 2550", "seats 2"]);
});
test("a paid order cannot be cancelled, and nothing runs", async () => {
const calls: string[] = [];
await assert.rejects(
applyAction(paidOrder, "cancel", fakeEffects(calls)),
/cannot cancel a paid order/,
);
assert.deepEqual(calls, []);
});
Run it with npx tsx --test order-states.test.ts:
✔ refunding a paid order returns the money, then frees the seats (0.712583ms)
✔ a paid order cannot be cancelled, and nothing runs (0.2385ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0
assert.rejects waits for the promise and passes only if it fails with a matching message. The “before” handlers printed straight to the console, so a test could only read the console or mock the services.
The next change: reserved orders
Here is Leo’s reserved status again, in the new code. Add one word to OrderStatus in types.ts:
export type OrderStatus = "pending" | "reserved" | "paid" | "cancelled" | "refunded";
Run npx tsc --noEmit now and it fails, because orderStates has no reserved object. The full message is longer, and this is its start:
order-states.ts(20,14): error TS2741: Property 'reserved' is missing in type '{ pending: ...
Add the object to orderStates, next to pending. This is an excerpt of order-states.ts, and the rest of the file stays the same:
reserved: {
pay: async () => "paid", // regular guests pay at the door: no ticket email
cancel: async (order, effects) => {
await effects.releaseSeats(order);
return "cancelled";
},
refund: refuse("refund"),
},
A reserved order for Ben now pays without an email and cancels with [seats] released 2 seats for spring. Every rule about reserved sits in this one object, and tsc wouldn’t let Maya skip the cancel line.
Rule: when the states sit in a
Record<OrderStatus, OrderState>,tscfails until every status answers every action.
When State is worth it
Use State when:
- the same status checks (
if (order.status !== "paid")) appear in several handlers - a new status means reading every handler to decide what it allows
- a status changes what an action does, not only whether it’s allowed, like the email for
reservedorders
Skip it when only one function reads the status, or when there are two statuses and no transitions. A switch on the status union, with the never check, is enough there. Also skip it when only the allowed moves matter, not what each action does. Then a table such as { pending: ["paid", "cancelled"], paid: ["refunded"] } lists the transitions in one line.
State costs one object per status, and every status must answer every action. So a new action means one line in each status object, which is four lines today. And to read what refund does, you open every status object.
Exercise: count the edits for a new action
Leo wants buyers to ask for their tickets again, an action named resendTickets. It’s allowed only for paid orders, it sends the tickets, and the order stays paid. Before you write code, predict how many places tsc will ask you to change.
Answer
Five. Add "resendTickets" to OrderAction, and tsc reports Property 'resendTickets' is missing four times, once for each status object. In pending, cancelled and refunded, write resendTickets: refuse("resendTickets"). In paid, write this step (an excerpt of orderStates):
resendTickets: async (order, effects) => {
await effects.sendTickets(order);
return "paid";
},
Command: turn admin actions into data
Bulk refunds that fail and disappear
When a show moves to a new date, Leo refunds many orders from the admin page. The card service sometimes times out. Here is the admin code, admin-before.ts, with fake services where the refund of order o3 times out:
// Fake services: the card service times out for order o3
async function refundOrder(orderId: string): Promise<void> {
if (orderId === "o3") throw new Error("card service timed out");
console.log(`[card] refunded order ${orderId}`);
}
async function cancelOrder(orderId: string): Promise<void> {
console.log(`[seats] released seats of order ${orderId}`);
}
// Leo's admin page: one loop per action, each with its own logging
async function bulkRefund(orderIds: string[]): Promise<void> {
for (const orderId of orderIds) {
try {
await refundOrder(orderId);
console.log(`[log] refund ${orderId} done`);
} catch (err: unknown) {
const reason = err instanceof Error ? err.message : String(err);
console.log(`[log] refund ${orderId} failed: ${reason}`);
}
}
}
async function bulkCancel(orderIds: string[]): Promise<void> {
for (const orderId of orderIds) {
try {
await cancelOrder(orderId);
console.log(`[log] cancel ${orderId} done`);
} catch (err: unknown) {
const reason = err instanceof Error ? err.message : String(err);
console.log(`[log] cancel ${orderId} failed: ${reason}`);
}
}
}
await bulkRefund(["o1", "o2", "o3"]);
await bulkCancel(["o4"]);
Pause and predict: the refund of
o3throws. Does the program stop there, or does the cancel ofo4still run? Write down the lines you expect, then compare.
Output:
[card] refunded order o1
[log] refund o1 done
[card] refunded order o2
[log] refund o2 done
[log] refund o3 failed: card service timed out
[seats] released seats of order o4
[log] cancel o4 done
The catch in bulkRefund logs the timeout and the loop ends normally. So bulkCancel still runs, and o4 is cancelled.
Leo’s third request was to retry failed refunds during the night and keep a record of every action. But in this code the failed refund of o3 exists only as a line in the log. The function call happened and is gone, so there’s nothing to keep and run again. Retry would have to be written into both loops, and every new admin action would copy the loop again.
The idea: write the request down
Command is a behavioral pattern from the GoF book that turns a request into an object holding everything needed to run it. Other code can then run it now, later, again, or never.
The GoF book names two more parts. The receiver is the code that does the real work, here the card and seat services. The invoker is the code that runs commands without knowing what they do, here a loop that logs and keeps failures.
In a restaurant kitchen, the waiter writes each order on a slip, and the slips wait on a rail. The cook makes them one by one, and if a dish burns, the slip goes back on the rail. Figure 6 puts the kitchen next to the code.
A restaurant TinyTickets admin page
a slip: "table 4, soup" { type: "refund", orderId: "o3" }
slips wait on the rail commands: AdminCommand[]
a burnt dish: the slip goes back failed commands are returned
Figure 6: the slip is data; anyone can count it, keep it or hand it back.
In the code, each request is an AdminCommand object in the commands array. runCommands is the invoker, and it hands back the commands that failed.
The fix: AdminCommand, execute and runCommands
Module 1 showed a command as tagged data, an object whose type field says what it is. The fix uses that form, because data can be logged and stored. Save admin-commands.ts:
// A command: one admin request, written down as plain data
export type AdminCommand =
| { type: "refund"; orderId: string }
| { type: "cancel"; orderId: string };
// The receiver: the code that knows how to do the work
export interface OrderActions {
refund(orderId: string): Promise<void>;
cancel(orderId: string): Promise<void>;
}
export function execute(command: AdminCommand, actions: OrderActions): Promise<void> {
switch (command.type) {
case "refund":
return actions.refund(command.orderId);
case "cancel":
return actions.cancel(command.orderId);
default: {
const unhandled: never = command; // compile error if a type is missing
return unhandled;
}
}
}
// The invoker: runs any command, logs it, and keeps the ones that failed
export async function runCommands(
commands: AdminCommand[],
actions: OrderActions,
): Promise<AdminCommand[]> {
const failed: AdminCommand[] = [];
for (const command of commands) {
try {
await execute(command, actions);
console.log(`[log] ${command.type} ${command.orderId} done`);
} catch (err: unknown) {
const reason = err instanceof Error ? err.message : String(err);
console.log(`[log] ${command.type} ${command.orderId} failed: ${reason}`);
failed.push(command);
}
}
return failed;
}
execute connects each command type to the receiver. runCommands holds the loop, the logging and the error handling, written once for every type. Save admin-main.ts:
import { runCommands, type AdminCommand, type OrderActions } from "./admin-commands.ts";
// Fake services: the card service times out for order o3
const actions: OrderActions = {
async refund(orderId) {
if (orderId === "o3") throw new Error("card service timed out");
console.log(`[card] refunded order ${orderId}`);
},
async cancel(orderId) {
console.log(`[seats] released seats of order ${orderId}`);
},
};
const commands: AdminCommand[] = [
{ type: "refund", orderId: "o1" },
{ type: "refund", orderId: "o2" },
{ type: "refund", orderId: "o3" },
{ type: "cancel", orderId: "o4" },
];
await runCommands(commands, actions);
It prints the same seven lines as admin-before.ts. The difference is what runCommands returns, which is the failed commands, as data. Figure 7 shows the structure before and after.
Before
[admin page] --> [bulkRefund] --> [refundOrder] loop + log + catch
[admin page] --> [bulkCancel] --> [cancelOrder] loop + log + catch
After
[admin-main.ts] ==> AdminCommand[] NEW
[admin-main.ts] --> [runCommands] --> [execute] NEW
[execute] --> [OrderActions] (I) NEW
[actions object in admin-main.ts] ..> [OrderActions] (I)
Figure 7: one loop serves every command type, and the request becomes a value you can keep.
Prove it with a test
The fake receiver fails for o3 and records the rest. Save admin-commands.test.ts:
import { test } from "node:test";
import assert from "node:assert/strict";
import { runCommands, type OrderActions } from "./admin-commands.ts";
test("runCommands runs every command and returns the failed ones", async () => {
const done: string[] = [];
const fakeActions: OrderActions = {
async refund(orderId) {
if (orderId === "o3") throw new Error("timeout");
done.push(`refund ${orderId}`);
},
async cancel(orderId) {
done.push(`cancel ${orderId}`);
},
};
const failed = await runCommands(
[
{ type: "refund", orderId: "o3" },
{ type: "cancel", orderId: "o4" },
],
fakeActions,
);
assert.deepEqual(done, ["cancel o4"]);
assert.deepEqual(failed, [{ type: "refund", orderId: "o3" }]);
});
Run it with npx tsx --test admin-commands.test.ts. The [log] lines come from runCommands:
[log] refund o3 failed: timeout
[log] cancel o4 done
✔ runCommands runs every command and returns the failed ones (0.98625ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0
The “before” loops called refundOrder by name, so a test had to mock that function to make it fail. And the test could check only the console, because the loops returned nothing.
The next change: retry tonight
With commands as data, Leo’s retry takes three new lines. Save admin-retry.ts:
import { runCommands, type AdminCommand, type OrderActions } from "./admin-commands.ts";
let cardServiceUp = false; // the fake card service is down at first
const actions: OrderActions = {
async refund(orderId) {
if (!cardServiceUp && orderId === "o3") throw new Error("card service timed out");
console.log(`[card] refunded order ${orderId}`);
},
async cancel(orderId) {
console.log(`[seats] released seats of order ${orderId}`);
},
};
const commands: AdminCommand[] = [
{ type: "refund", orderId: "o1" },
{ type: "refund", orderId: "o2" },
{ type: "refund", orderId: "o3" },
{ type: "cancel", orderId: "o4" },
];
const failed = await runCommands(commands, actions);
console.log(`saved for tonight: ${JSON.stringify(failed)}`); // NEW
cardServiceUp = true; // later that night
const stillFailed = await runCommands(failed, actions); // NEW
console.log(`still failing: ${stillFailed.length}`); // NEW
The output ends with:
saved for tonight: [{"type":"refund","orderId":"o3"}]
[card] refunded order o3
[log] refund o3 done
still failing: 0
JSON.stringify(failed) turns the failed commands into a string. That string can go into a database table, and a scheduled job can read it back tonight. Here it stays in a variable to keep the example short. A command read back from storage has the type unknown again, so check its fields before you run it, as Module 1 checked the request body.
When Command is worth it
Use Command when:
- an action must run later, in another process, or again after a failure
- you need a record of who asked for what, in one format
- you see the same loop, logging and
try/catchcopied around different actions
Skip it when the action runs once, right away, and nobody needs to see it again. A direct call, await refundOrder(orderId), is clearer. Also skip it when you build the commands and run them on the next line, with no logging, retry or storage, because the layer then adds nothing.
Command costs a union of command types, an execute function and an invoker. So every new action needs a union member, a case and a receiver method. Stored commands add one more duty, because commands saved last week must still run after you rename a field.
Exercise: resend tickets to a new address
Ana changed her email address. Leo wants an admin command that resends an order’s tickets to a given address. Add it, and note what tsc tells you along the way.
Answer
Add | { type: "resend"; orderId: string; email: string } to AdminCommand, and resend(orderId: string, email: string): Promise<void>; to OrderActions. Now tsc reports that the resend command is not assignable to type 'never' in execute. Add the case:
case "resend":
return actions.resend(command.orderId, command.email);
Inside this case, TypeScript knows command has an email field. runCommands doesn’t change, so the new command gets logging and failure handling with no new code. With a fake resend that prints, running [{ type: "resend", orderId: "o1", email: "ana.new@example.com" }] prints the fake’s line and [log] resend o1 done.
Template Method: fixed steps in a base class
Module 1 showed ShowImport, whose run method parses and saves each line, while each subclass writes parse. Template Method is the GoF name for that shape, where a base class fixes the order of the steps and subclasses fill in one or more of them. Figure 8 shows it with a second subclass added.
[ShowImport] run(): parse each line, save, count
[CommaImport extends ShowImport] fills in parse() for "a,b" lines
[TabImport extends ShowImport] NEW fills in parse() for tab lines
[nightly show import] --> [ShowImport] calls run(), never parse()
Figure 8: the base class owns the steps; a subclass owns one step.
You meet it in Node.js streams, which Module 8 teaches. A custom Readable stream extends stream.Readable and writes _read(), and the Node.js docs say only the internal Readable methods call _read().
So you need Template Method when a framework asks you to extend its class and fill in a method. In your own code, pass the varying step as a function parameter instead. That’s Strategy, and it needs no class tree.
Strategy and State side by side
Strategy and State look the most alike, so Figure 9 draws them with the same layout. The one difference is marked with *.
Strategy State
[checkout-main.ts] [applyAction]
picks providers["wallet"] reads order.status
[checkout] --> [PaymentProvider] (I) [applyAction] --> [OrderState] (I)
[WalletProvider] ..> [PaymentProvider] [orderStates.paid] ..> [OrderState]
* the caller picks, once * * the status picks, and each step *
* returns the next status *
Figure 9: the same shape; in Strategy the caller chooses, in State the object’s own status chooses.
Figure 10 is the decision figure for this module. It starts from the problem in your code, and its first exit is “no pattern”.
The behavior must differ between cases
|
v
2 or 3 stable cases, in one function? -- yes --> No pattern needed:
| no if or switch on a union
v
"How to do one step", picked by the caller? -- yes --> Strategy
| no (object map or class)
v
What is allowed depends on a status? -- yes --> State
| no
v
The action must be stored, logged or retried? -- yes --> Command
| no
v
A framework class asks you to fill in one method? -- yes --> Template Method
| no
v
No pattern needed; go back to Module 1
Figure 10: each exit after the first names the problem the pattern solves.
Check yourself
- In the Strategy fix, what does
checkoutknow about the wallet’s $100 limit? - Why does
Record<OrderStatus, OrderState>catch a missing status, while the “before” handlers did not? - What is the one-line difference between Strategy and State?
- Why does the Command fix use plain data instead of objects with an
executemethod? - You need to add a new action to
orderStates. How many places change, and why is that the cost of State?
Answers
- Nothing. The limit is a private field of
WalletProvider, set incheckout-main.ts, andcheckoutonly reads thePaymentResult. Recordrequires one key for every member of the union, sotscfails when a status has no object. The handlers compared the status with!==, which compiles for any union.- In Strategy, the caller picks the behavior once. In State, the object’s current status picks it, and each step moves the object to its next status.
- Data can be saved as JSON, logged in one format and run again later or in another process. An object’s methods are lost when you turn it into JSON.
- One for the action name in
OrderAction, plus one line in every status object. State makes a new status cheap and a new action more expensive.
Lab: block seats for regular guests
Time: about 20 minutes. Put the files in a folder set up as in Module 1.
Here is the seat code, seats.ts. A buyer holds a seat during checkout, then the seat is sold or released:
export type Seat = { id: string; isHeld: boolean; isSold: boolean; heldBy: string | null };
export function hold(seat: Seat, buyerEmail: string): Seat {
if (seat.isSold) throw new Error(`cannot hold a sold seat`);
if (seat.isHeld) throw new Error(`cannot hold a held seat`);
return { ...seat, isHeld: true, heldBy: buyerEmail };
}
export function release(seat: Seat): Seat {
if (!seat.isHeld) throw new Error(`cannot release a seat that is not held`);
return { ...seat, isHeld: false, heldBy: null };
}
export function sell(seat: Seat): Seat {
if (seat.isSold) throw new Error(`cannot sell a sold seat`);
if (!seat.isHeld) throw new Error(`cannot sell a seat that is not held`);
return { ...seat, isHeld: false, isSold: true };
}
Leo wants to block seats for his regular guests. Buyers can’t hold or buy a blocked seat. Leo can unblock it, and then it’s free again.
The two booleans already allow a seat that is both held and sold, which makes no sense. A third boolean, isBlocked, would add more such cases, and every function would need another check. Refactor seats.ts so that this test file, seats.test.ts, passes:
import { test } from "node:test";
import assert from "node:assert/strict";
import { act, type Seat } from "./seats.ts";
const free: Seat = { id: "A1", status: "free", heldBy: null };
test("a buyer holds a free seat, then buys it", () => {
const held = act(free, "hold", "ana@example.com");
assert.deepEqual(held, { id: "A1", status: "held", heldBy: "ana@example.com" });
const sold = act(held, "sell", "ana@example.com");
assert.deepEqual(sold, { id: "A1", status: "sold", heldBy: "ana@example.com" });
});
test("a released seat is free again", () => {
const held = act(free, "hold", "ana@example.com");
assert.deepEqual(act(held, "release", "ana@example.com"), free);
});
test("a sold seat refuses every action", () => {
const sold = act(act(free, "hold", "ana@example.com"), "sell", "ana@example.com");
assert.throws(() => act(sold, "hold", "ben@example.com"), /cannot hold a sold seat/);
assert.throws(() => act(sold, "release", "leo"), /cannot release a sold seat/);
});
test("Leo blocks a seat for a regular guest, and buyers cannot hold it", () => {
const blocked = act(free, "block", "leo");
assert.deepEqual(blocked, { id: "A1", status: "blocked", heldBy: null });
assert.throws(() => act(blocked, "hold", "ben@example.com"), /cannot hold a blocked seat/);
assert.throws(() => act(blocked, "sell", "ben@example.com"), /cannot sell a blocked seat/);
assert.deepEqual(act(blocked, "unblock", "leo"), free);
});
The third argument of act says who acts, a buyer’s email or "leo". Run the test with npx tsx --test seats.test.ts, and check types with npx tsc --noEmit. Against the old seats.ts, the test fails and tsc reports that act does not exist.
Pause and predict: before you start, list the statuses and the actions. Which pattern from this module fits, and what replaces the two booleans?
Hint 1
Replace isHeld and isSold with one field, status, whose type is the union "free" | "held" | "sold" | "blocked". A seat can now be in exactly one status.
Hint 2
Follow orderStates. Write type SeatAction = "hold" | "release" | "sell" | "block" | "unblock", and give each status one object with one function per action. These functions need no await, so they can be plain functions that return the new seat.
Hint 3
Write a refuse(action) helper that throws cannot ${action} a ${seat.status} seat. Then act(seat, action, by) is one line, seatStates[seat.status][action](seat, by).
Solution
seats.ts:
export type SeatStatus = "free" | "held" | "sold" | "blocked";
export type SeatAction = "hold" | "release" | "sell" | "block" | "unblock";
export type Seat = { id: string; status: SeatStatus; heldBy: string | null };
type Step = (seat: Seat, by: string) => Seat;
type SeatState = Record<SeatAction, Step>;
const refuse = (action: SeatAction): Step => (seat) => {
throw new Error(`cannot ${action} a ${seat.status} seat`);
};
const seatStates: Record<SeatStatus, SeatState> = {
free: {
hold: (seat, by) => ({ ...seat, status: "held", heldBy: by }),
release: refuse("release"),
sell: refuse("sell"),
block: (seat) => ({ ...seat, status: "blocked" }),
unblock: refuse("unblock"),
},
held: {
hold: refuse("hold"),
release: (seat) => ({ ...seat, status: "free", heldBy: null }),
sell: (seat) => ({ ...seat, status: "sold" }),
block: refuse("block"),
unblock: refuse("unblock"),
},
sold: {
hold: refuse("hold"),
release: refuse("release"),
sell: refuse("sell"),
block: refuse("block"),
unblock: refuse("unblock"),
},
blocked: {
hold: refuse("hold"),
release: refuse("release"),
sell: refuse("sell"),
block: refuse("block"),
unblock: (seat) => ({ ...seat, status: "free" }),
},
};
export function act(seat: Seat, action: SeatAction, by: string): Seat {
return seatStates[seat.status][action](seat, by);
}
Output of npx tsx --test seats.test.ts:
✔ a buyer holds a free seat, then buys it (0.674ms)
✔ a released seat is free again (0.072792ms)
✔ a sold seat refuses every action (0.199917ms)
✔ Leo blocks a seat for a regular guest, and buyers cannot hold it (0.09675ms)
ℹ tests 4
ℹ pass 4
ℹ fail 0
The union removed the impossible “held and sold” seat. Each status answers all five actions, so tsc would have stopped you if blocked had no answer for hold. The sold object is all refusals, which is long but states the rule plainly.
This solution leaves two things as they were. First, anyone can call act(seat, "block", "ben@example.com"), because the by argument isn’t checked. Checking that only Leo may block is a permission rule, and it belongs in the route that knows who is logged in. Second, a sold seat keeps heldBy, as the old sell did, so the order still shows who bought it.
Which pattern, if any?
Scenario 1: a receipt title for refunded orders
The receipt code has one status check, in receipt-before.ts:
import type { Order } from "./types.ts";
export function receiptTitle(order: Order): string {
if (order.status === "paid") return `Your tickets for Songs of Spring (order ${order.id})`;
return `Order ${order.id}`;
}
console.log(receiptTitle({ id: "o1", showId: "spring", buyerEmail: "ana@example.com",
quantity: 2, totalCents: 2550, status: "paid" }));
It prints Your tickets for Songs of Spring (order o1). The new requirement is that receipts of refunded orders start with Refunded:, and receipts of cancelled orders with Cancelled:. Which pattern, if any?
Hint
How many places read the status for this, and does anything move the order to a new status here?
A strong answer
No pattern. One function reads the status, and it changes nothing, so there are no transitions for State to own. A switch on the union with the never check is enough, and tsc will flag the function when a status such as reserved is added. receipt-after.ts:
import type { Order } from "./types.ts";
export function receiptTitle(order: Order): string {
switch (order.status) {
case "paid":
return `Your tickets for Songs of Spring (order ${order.id})`;
case "refunded":
return `Refunded: order ${order.id}`;
case "cancelled":
return `Cancelled: order ${order.id}`;
case "pending":
return `Order ${order.id}`;
default: {
const unhandled: never = order.status;
return unhandled;
}
}
}
const order: Order = { id: "o1", showId: "spring", buyerEmail: "ana@example.com",
quantity: 2, totalCents: 2550, status: "paid" };
console.log(receiptTitle(order));
console.log(receiptTitle({ ...order, status: "refunded" }));
Output:
Your tickets for Songs of Spring (order o1)
Refunded: order o1
Moving this into orderStates would mix display text with the rules for payments and refunds. Keep it a switch until several functions repeat the same status checks.
Scenario 2: announcements at 9:00 on show day
Leo’s admin page sends an announcement to every buyer of a show, right away. Here is announce-before.ts:
async function sendAnnouncement(showId: string, text: string): Promise<void> {
console.log(`[mail] to every buyer of ${showId}: ${text}`);
}
// Leo's admin page: "Send now"
await sendAnnouncement("spring", "Doors open at 19:00.");
Now Leo wants to write announcements in the evening and have them sent at 9:00 on the show day. He also wants to cancel a planned announcement before it goes out. Which pattern, if any?
Hint
The way the email is sent does not change. What changes is when it runs, and whether it runs at all.
A strong answer
Command, in the data form. Each planned announcement becomes a record with a time, kept until it’s due, and cancelling it removes the record. Strategy doesn’t fit, because the sending doesn’t vary. announce-after.ts:
type Announce = { type: "announce"; id: string; showId: string; text: string; runAt: string };
// In TinyTickets this array is a table; here it lives in memory
const scheduled: Announce[] = [];
async function sendAnnouncement(showId: string, text: string): Promise<void> {
console.log(`[mail] to every buyer of ${showId}: ${text}`);
}
function schedule(command: Announce): void {
scheduled.push(command);
}
function cancelScheduled(id: string): void {
const index = scheduled.findIndex((command) => command.id === id);
if (index !== -1) scheduled.splice(index, 1);
}
// A scheduled job calls this every minute
async function runDue(now: string): Promise<void> {
for (const command of scheduled.filter((c) => c.runAt <= now)) {
await sendAnnouncement(command.showId, command.text);
cancelScheduled(command.id);
}
}
schedule({ type: "announce", id: "a1", showId: "spring", text: "Doors open at 19:00.",
runAt: "2027-03-14T09:00" });
schedule({ type: "announce", id: "a2", showId: "spring", text: "Parking is full.",
runAt: "2027-03-14T09:00" });
cancelScheduled("a2"); // Leo changed his mind
await runDue("2027-03-14T08:59");
console.log(`waiting: ${scheduled.length}`);
await runDue("2027-03-14T09:00");
console.log(`waiting: ${scheduled.length}`);
Output:
waiting: 1
[mail] to every buyer of spring: Doors open at 19:00.
waiting: 0
Times in the same YYYY-MM-DDTHH:MM format sort as text in time order, so <= works on them. If a send throws, runDue stops and the command stays in the list, so the next run tries it again.
Get feedback on your answer
Copy this prompt into an AI assistant, with your answer below it:
I am learning design patterns in TypeScript. Here is a scenario, the code,
a new requirement, and my answer: which pattern I would use (Strategy,
State, Command, Template Method, or none) and my code. Tell me whether my
choice fits the problem in the code, what a simpler option would be, and
one cost my choice adds. Do not rewrite my whole answer; point to the
lines that matter.
Scenario and code:
<paste here>
My answer:
<paste here>
Going deeper
You can skip this section. It covers other forms of the three patterns and where you meet them outside TinyTickets.
Function form of Strategy
When a strategy is one function with little setup, a function type is shorter than an interface and a class. That’s the priceRules form from Module 1. Here it would be type Charge = (amountCents: number) => Promise<PaymentResult>, with a closure that keeps the wallet limit where the class kept a private field. Use classes or objects when the strategy has several methods (charge and refund), holds a client, or is registered in a framework such as NestJS (Module 6).
Class form of State
The GoF book shows State with one class per status. The order is an object that holds its current state object, and each state object picks the next one. That suits an object that lives in memory, such as a seat hold with a timer. But a web backend usually loads an order from the database, acts, and saves it again. For that, the object map above is shorter, keeps the order as plain JSON, and gives you the missing-status check from Record.
Object form of Command, for undo
The GoF book shows each command as an object with an execute method, and often an undo method. That form fits undo, because each command knows how to reverse itself. Save undo-commands.ts:
// The object form: each command carries its own execute and undo
interface Command {
readonly label: string;
execute(): Promise<void>;
undo(): Promise<void>;
}
class BlockSeatsCommand implements Command {
readonly label: string;
#seatIds: string[];
constructor(seatIds: string[]) {
this.#seatIds = seatIds;
this.label = `block ${seatIds.join(", ")}`;
}
async execute(): Promise<void> {
console.log(`[seats] blocked ${this.#seatIds.join(", ")}`);
}
async undo(): Promise<void> {
console.log(`[seats] unblocked ${this.#seatIds.join(", ")}`);
}
}
const history: Command[] = [];
async function run(command: Command): Promise<void> {
await command.execute();
history.push(command);
}
async function undoLast(): Promise<void> {
const last = history.pop();
if (last === undefined) return; // nothing to undo
await last.undo();
console.log(`undid "${last.label}"`);
}
await run(new BlockSeatsCommand(["A1", "A2"]));
await run(new BlockSeatsCommand(["B7"]));
await undoLast();
Output:
[seats] blocked A1, A2
[seats] blocked B7
[seats] unblocked B7
undid "block B7"
An object with methods can’t be saved as JSON and run in another process, because its methods are lost. So use the object form for undo inside one running process, and the data form when commands are stored, queued or sent to a worker. A closure such as () => actions.refund("o3") is a third form, with the same limit as the object form.
Where you meet these patterns
Array.prototype.sorttakes a compare function, which is Strategy in function form.- Passport, a login library for Express, calls its login methods “strategies” and registers each one with
passport.use(strategy). - A state machine is a set of statuses and the transitions allowed between them, as in Figure 5. XState is a library that describes them as data and refuses moves you didn’t list. It helps when statuses have nested statuses, timers or many transitions.
- The AWS SDK for JavaScript v3 sends every request as a command object, such as
client.send(new ListTablesCommand({})). - BullMQ is a Node.js library that stores jobs until a worker process runs them. It requires job data that survives
JSON.stringify, so a job is a command in the data form.
Patterns people mix up with these
- Factory (Module 2). A factory creates the provider, and Strategy uses any provider through one interface. A factory function can build the
providersmap. - An event (Module 5). A command says “do this” and has one handler. An event says “this happened”, and any number of listeners may react.
Cheat sheet
| Pattern | The signal in your code | What it costs |
|---|---|---|
| Strategy | The same if (method === ...) in more than one file |
An interface, one class per provider, a place that picks |
| State | if (order.status !== ...) at the top of many handlers |
One object per status; a new action touches every status |
| Command | Copied loops with try/catch and logging per action |
A union, an execute and an invoker; stored commands must stay readable |
| Template Method | A framework asks you to extend a class and fill in a method | The subclass depends on the base class’s order of calls |
| No pattern | Two or three stable cases in one place | Nothing; a switch on a union with the never check |
- Strategy: the caller passes in how one step is done, so
checkoutnever names a provider and a test can pass a fake. - State: each status answers every action, and a
Record<OrderStatus, OrderState>makestscfail when a status is missing. - Command: a request written down as plain data can be logged, kept and run again, and
runCommandsreturns the ones that failed. - Template Method: use it when a framework asks for a subclass; in your own code, pass a function instead.
- First check: two or three stable cases in one function need no pattern.
Next, Module 5 looks at what happens after an order is paid, when several parts of TinyTickets must react and the paying code shouldn’t know about any of them.
Sources
- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994. The names, intents and roles (receiver, invoker) of Strategy, State, Command and Template Method.
- TypeScript handbook: narrowing and exhaustiveness checking, utility types (
Record), type compatibility. - MDN: private class fields,
Array.prototype.sort. - Node.js documentation: test runner, assert, streams,
readable._read. - Passport: strategies.
- XState: documentation.
- AWS SDK for JavaScript v3: README.
- BullMQ: job data.