Leo asked Maya for one small change. “Can we text buyers when their order is paid?” he wrote. Maya opened checkout.ts. The POST /checkout handler was 300 lines long, and the email code sat in the middle of it.
Three days later, the text messages worked, and the booking fee was wrong for groups. The change itself was ten lines. The three days went into finding where those lines could go, and into testing by hand.
Maya, Leo and TinyTickets are invented, and so are the numbers in their story.
This module shows why code like Maya’s is hard to change, and the three ideas that every later pattern uses. It teaches no single pattern in full. It gives you what you need to read the rest of the course.
After this module, you can:
- find the three common causes of hard-to-change code in a Node.js route handler
- apply three ideas to TinyTickets code: separate what changes, depend on an interface, and combine small functions instead of inheriting from classes
- say what a pattern costs, and tell when a change needs no pattern at all
- read the figures used in every module of this course
Set up a folder for the examples
Every example in this course is a complete file that you run with one command. You need Node.js 26, the current long-term-support (LTS) release, which the Node.js team fixes for the longest time. Make a folder and install the tools:
mkdir patterns
cd patterns
npm init -y
npm pkg set type=module
npm install express
npm install --save-dev tsx typescript @types/node @types/express
The commands install three tools:
- tsx. tsx is a command that runs a TypeScript file directly, with no build step. See tsx.is.
- TypeScript. It gives you
tsc, the type checker.tsc --noEmitchecks your types and writes no files. - Express 5. The web framework that the first example uses.
npm pkg set type=module tells Node.js to treat your files as ES modules, files that use import and export. Then put this tsconfig.json in the folder:
{
"compilerOptions": {
"target": "ES2023",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"skipLibCheck": true,
"types": ["node"]
}
}
"strict": true turns on all of TypeScript’s strict checks. allowImportingTsExtensions lets you import a file by its real name, such as "./fakes.ts", which is what tsx and Node.js expect.
Add the fake service clients
TinyTickets talks to four outside services: payments, email, SMS and push notifications. A company gives you an SDK, a library for calling its service. In this course, each SDK is a fake, a class that prints a line instead of calling the real service. Save the four fakes as fakes.ts:
// Fake SDKs for TinyTickets. They print instead of calling a real service.
export class PayClient {
constructor(apiKey: string) {
if (apiKey === "") throw new Error("PayClient needs an API key");
}
async charge(amountCents: number): Promise<{ id: string }> {
console.log(`[pay] charged ${amountCents} cents`);
return { id: "ch_1" };
}
}
export class MailClient {
constructor(host: string) {
if (host === "") throw new Error("MailClient needs a host");
}
async send(to: string, subject: string): Promise<void> {
console.log(`[mail] to ${to}: ${subject}`);
}
}
export class SmsClient {
constructor(apiKey: string) {
if (apiKey === "") throw new Error("SmsClient needs an API key");
}
async send(to: string, text: string): Promise<void> {
console.log(`[sms] to ${to}: ${text}`);
}
}
export class PushClient {
async send(deviceToken: string, text: string): Promise<void> {
console.log(`[push] to ${deviceToken}: ${text}`);
}
}
Three of the four classes need a setting when you create them, as a real SDK does. So whoever writes new PayClient(...) must know the API key, and Module 2 starts from that problem.
Maya’s checkout handler does six jobs
Here is Maya’s handler, cut down from 300 lines to the parts that matter. It keeps the same shape, with every job inside one function. Save it as checkout.ts:
import express from "express";
import { MailClient, PayClient } from "./fakes.ts";
const shows = new Map([["spring", { title: "Songs of Spring", priceCents: 1200 }]]);
const orders: { id: number; showId: string; totalCents: number }[] = [];
const app = express();
app.use(express.json());
app.post("/checkout", async (req, res) => {
const body: unknown = req.body;
if (
typeof body !== "object" || body === null ||
!("showId" in body) || typeof body.showId !== "string" ||
!("quantity" in body) || typeof body.quantity !== "number" ||
!("email" in body) || typeof body.email !== "string"
) {
res.status(400).json({ error: "bad input" });
return;
}
const show = shows.get(body.showId);
if (show === undefined) {
res.status(404).json({ error: "no such show" });
return;
}
const fee = body.quantity >= 4 ? 0 : 150; // no booking fee for groups
const totalCents = show.priceCents * body.quantity + fee;
const pay = new PayClient(process.env.PAY_KEY ?? "test-key");
await pay.charge(totalCents);
const order = { id: orders.length + 1, showId: body.showId, totalCents };
orders.push(order);
const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
await mail.send(body.email, `Your tickets for ${show.title}`);
res.status(201).json(order);
});
app.listen(3000, () => console.log("TinyTickets listening on port 3000"));
Run it with npx tsx checkout.ts. Then send an order from a second terminal:
curl -s -X POST localhost:3000/checkout -H 'content-type: application/json' -d '{"showId":"spring","quantity":2,"email":"ana@example.com"}'
The server prints:
TinyTickets listening on port 3000
[pay] charged 2550 cents
[mail] to ana@example.com: Your tickets for Songs of Spring
Then curl prints {"id":1,"showId":"spring","totalCents":2550}.
Two details in this code come back in later modules. The body arrives as unknown, a TypeScript type that allows nothing until you check it. After the typeof and in checks, TypeScript knows the body has the three fields the handler needs. The ?? operator uses its right side when the left side is null or undefined.
The code works, and for one show with one payment provider it’s fine. The trouble starts with the next change. Figure 1 shows what the handler holds.
+---------------------------+
(Buyer) --> | POST /checkout handler |
| 1 check the input |
| 2 find the show |
| 3 add the booking fee |
| 4 charge the buyer | ==> [PayClient]
| 5 save the order |
| 6 email the tickets | ==> [MailClient]
+---------------------------+
Legend
(Name) a person
[name] a module, function or class
A --> B A calls B
A ==> B A creates B (with "new" or a factory function)
Figure 1: one handler does six jobs and creates both clients itself.
A factory function is a function that creates an object and returns it, so its caller doesn’t write new.
What a design pattern is
A design pattern is a named answer to a design problem that keeps coming back. The best-known list is the 1994 book Design Patterns, which describes 23 patterns for object-oriented code. Its four authors are called the Gang of Four, or GoF.
A pattern has three parts that you should be able to say out loud:
- the problem: what change keeps hurting
- the answer: how the code is arranged so that change hurts less
- the cost: what you pay in files, in jumps between files, and in reading time
A pattern is an idea, not a library or a class diagram to copy. In TypeScript, the answer is often one function or one object, and the book’s class diagram would only add lines. More patterns also don’t make better code, because each one adds the cost in its third part.
A pattern gives you a tested shape for a common problem, so you don’t invent one under time pressure. It also gives you a shared word. If you and a teammate both know a pattern, its name says in one word what would otherwise need a drawing.
Three reasons Node.js code becomes hard to change
Code is hard to change when one small request forces you to edit many places. It’s also hard when you can’t check an edit without running the whole app. In Node.js backends, three causes come up again and again.
Route handlers that do everything
Maya’s handler in Figure 1 is the first cause. It mixes six jobs: check the input, find the show, add the booking fee, charge the buyer, save the order and email the tickets.
Leo’s text-message request touches job 6. To add it, Maya must read all six jobs and find a safe place between them. Then she must test the whole route, because no job can run on its own.
The booking-fee bug from the opening scene came from the same place. While she added the SMS code, Maya moved the fee line by accident. Nothing failed until a group of four paid the wrong total.
Clients created deep inside business logic
The second cause is harder to see, because the code looks clean. Business logic is the code for the rules about orders, shows and prices. Here, a business rule calls a helper, and the helper creates its own client. Save this as deep-client.ts:
import { MailClient } from "./fakes.ts";
// orders.ts: a business rule
async function confirmOrder(orderId: number, email: string): Promise<void> {
if (orderId <= 0) throw new Error(`bad order id ${orderId}`);
await sendConfirmation(email, orderId);
}
// email.ts: two files away, a client is created on every call
async function sendConfirmation(email: string, orderId: number): Promise<void> {
const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
await mail.send(email, `Order ${orderId} is confirmed`);
}
await confirmOrder(7, "ana@example.com");
Output:
[mail] to ana@example.com: Order 7 is confirmed
In a real project, these two functions live in two files, as the comments say. Now try to test confirmOrder. Every test run sends a real email, because nothing lets the test replace the MailClient.
So your choices are a mocking library or a test that needs a mail server. A mocking library is a tool that swaps an imported module for a stand-in during a test. In Figure 2, the ==> arrow sits at the end of the chain, where no caller can reach it.
[route] --> [confirmOrder] --> [sendConfirmation] ==> [MailClient]
orders.ts email.ts
A test of confirmOrder also runs sendConfirmation, and it creates
a real MailClient. No caller can hand in a different one.
Figure 2: a client created at the end of the chain cannot be replaced from the start.
Events and callbacks with no clear owner
The third cause comes from a Node.js strength. The built-in node:events module gives you EventEmitter, an object that calls a list of functions when you emit an event name. Each of those functions is a listener. Teams often make one shared emitter and import it everywhere. Save this as no-owner.ts:
import { EventEmitter } from "node:events";
// bus.ts: one shared emitter that every file imports
const bus = new EventEmitter();
// email.ts: adds a listener when the file is imported
bus.on("order:paid", (orderId: number) => console.log(`[mail] receipt for order ${orderId}`));
// seats.ts: a listener that emits a second event
bus.on("order:paid", (orderId: number) => bus.emit("seats:changed", orderId));
// seatmap.ts: a third file listens for the second event
bus.on("seats:changed", (orderId: number) => console.log(`[seats] refresh map after order ${orderId}`));
// checkout.ts: the sender cannot see who listens
bus.emit("order:paid", 7);
const heard = bus.emit("order:payed", 8); // a typo
console.log("anyone heard order:payed?", heard);
Output:
[mail] receipt for order 7
[seats] refresh map after order 7
anyone heard order:payed? false
Each line is short, but the whole flow is hard to follow. The sender in checkout.ts can’t see who reacts. A listener runs only if its file was imported somewhere.
A typo in an event name fails silently, because emit returns false and nothing else happens. Figure 3 shows the path of one order:paid event across four files.
[checkout.ts] --> [bus] emits "order:paid"
[bus] --> [email.ts listener]
[bus] --> [seats.ts listener]
[seats.ts listener] --> [bus] emits "seats:changed"
[bus] --> [seatmap.ts listener]
No file owns this flow. To learn what "order:paid" does,
you search the whole project for the string.
Figure 3: one event fans out across four files, and no file shows the whole path.
The trouble is the missing owner. Module 5 shows how to give events a typed list of names and one place that wires the listeners.
Three ideas under every pattern
Every pattern in this course applies one or more of three ideas. Learn them here with small code, and you’ll recognize them inside every later pattern.
Idea 1: separate what changes from what stays the same
Before you reach for a pattern, ask which part of the code keeps changing and which part stays the same. Then put them in different places.
Leo sells three ticket types. Students pay 20% less, and VIP tickets cost $5 more each. Every order under four tickets also pays a $1.50 booking fee. Here is the price code, total-before.ts:
type TicketType = "standard" | "student" | "vip";
function totalCents(type: TicketType, priceCents: number, quantity: number): number {
let subtotal = priceCents * quantity;
if (type === "student") {
subtotal = Math.round(subtotal * 0.8);
} else if (type === "vip") {
subtotal = subtotal + 500 * quantity;
}
const fee = quantity >= 4 ? 0 : 150;
return subtotal + fee;
}
console.log(totalCents("standard", 1200, 2)); // 2550
console.log(totalCents("student", 1200, 2)); // 2070
console.log(totalCents("vip", 1200, 4)); // 6800
Output:
2550
2070
6800
TicketType is a union type, which means its value must be one of the three listed strings.
Leo adds ticket types often: early bird, family, crew. The fee rule and the order of the steps have not changed in a year. But with an if chain, every new type means editing the middle of totalCents, next to the fee line that must not move.
Pause and predict: which lines change when Leo adds an “earlyBird” type, and which lines never change? How would you put the changing lines somewhere else? Write your answer before you read on.
Here is total-after.ts. The rules move into an object map, an object whose keys are the ticket types and whose values are functions:
type TicketType = "standard" | "student" | "vip";
type PriceRule = (subtotal: number, quantity: number) => number;
// What changes: one rule per ticket type
const priceRules: Record<TicketType, PriceRule> = {
standard: (subtotal) => subtotal,
student: (subtotal) => Math.round(subtotal * 0.8),
vip: (subtotal, quantity) => subtotal + 500 * quantity,
};
// What stays the same: subtotal, rule, fee
function totalCents(type: TicketType, priceCents: number, quantity: number): number {
const subtotal = priceRules[type](priceCents * quantity, quantity);
const fee = quantity >= 4 ? 0 : 150;
return subtotal + fee;
}
console.log(totalCents("standard", 1200, 2)); // 2550
console.log(totalCents("student", 1200, 2)); // 2070
console.log(totalCents("vip", 1200, 4)); // 6800
The output is the same three numbers. Record<TicketType, PriceRule> is a built-in TypeScript type. It describes an object with exactly one key for each member of TicketType, each holding a PriceRule.
So if you add "earlyBird" to TicketType and forget its rule, tsc reports that the property earlyBird is missing. Adding a type is now one word in the union and one line in the map, and totalCents doesn’t change. Figure 4 shows the move, and NEW marks the part the change added.
Before After
+------------------------+ +------------------------+
| [totalCents] | | [totalCents] |
| subtotal | | subtotal | --> [priceRules] NEW
| if student ... | | fee | standard
| else if vip ... | +------------------------+ student
| fee | vip
+------------------------+
Figure 4: the rules that change move into priceRules; totalCents keeps the steps that stay.
Rule: Put the part that keeps changing in its own place, so the steps around it stay as they are.
With two or three stable cases, the if chain is fine, and so is a switch. Move the rules out when they change more often than the code around them. Module 4 turns this idea into the Strategy pattern.
Idea 2: depend on an interface, not on a concrete class
An interface in TypeScript is a named shape, a list of properties and methods with their types. A concrete class is one real implementation, such as SmsClient. When your function creates the concrete class itself, as in Figure 2, nobody can swap it. Here is a reminder that TinyTickets sends on the day of a show, remind-before.ts:
import { SmsClient } from "./fakes.ts";
async function remindBuyer(phone: string, showTitle: string): Promise<void> {
const sms = new SmsClient(process.env.SMS_KEY ?? "test-key");
await sms.send(phone, `Tonight: ${showTitle}. Doors open at 19:00.`);
}
await remindBuyer("+15550100", "Songs of Spring");
Output:
[sms] to +15550100: Tonight: Songs of Spring. Doors open at 19:00.
Suppose you want a test that checks the text of the reminder. With this code, the test can only run the real SmsClient, or replace the ./fakes.ts import with a mocking library.
Pause and predict: what is the smallest change that lets a test pass in its own sender? Who should create the
SmsClientinstead?
The fix has two parts. First, remindBuyer asks for “something with a send method” and stops creating it. Then the caller creates the real client. Save remind.ts:
export interface TextSender {
send(to: string, text: string): Promise<void>;
}
export async function remindBuyer(
sender: TextSender,
phone: string,
showTitle: string,
): Promise<void> {
await sender.send(phone, `Tonight: ${showTitle}. Doors open at 19:00.`);
}
Then save remind-main.ts, the file that runs it:
import { SmsClient } from "./fakes.ts";
import { remindBuyer } from "./remind.ts";
const sms = new SmsClient(process.env.SMS_KEY ?? "test-key");
await remindBuyer(sms, "+15550100", "Songs of Spring");
npx tsx remind-main.ts prints the same line as before. SmsClient never mentions TextSender, but it still fits, because its send method has the right shape. Figure 5 shows the change in the arrows. [TextSender] (I) marks an interface, and A ..> B means A has the shape that interface B asks for.
Before
[remindBuyer] ==> [SmsClient]
After
[remind-main.ts] ==> [SmsClient] ..> [TextSender] (I) NEW
[remind-main.ts] --> [remindBuyer] --> [TextSender] (I)
[remind.test.ts] ==> [fakeSender] ..> [TextSender] (I) NEW
Figure 5: remindBuyer now calls an interface; whoever runs it decides what fills that interface.
Now the test. Node.js has a built-in test runner, node:test, and an assertion module, node:assert. The test passes in a fake sender, a plain object that records each text it gets. Save remind.test.ts:
import { test } from "node:test";
import assert from "node:assert/strict";
import { remindBuyer, type TextSender } from "./remind.ts";
test("remindBuyer texts the show title and door time", async () => {
const sent: string[] = [];
const fakeSender: TextSender = {
async send(to, text) {
sent.push(`${to} | ${text}`);
},
};
await remindBuyer(fakeSender, "+15550100", "Songs of Spring");
assert.deepEqual(sent, ["+15550100 | Tonight: Songs of Spring. Doors open at 19:00."]);
});
Run it with npx tsx --test remind.test.ts:
✔ remindBuyer texts the show title and door time (1.105458ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0
The time and a few summary lines differ on your machine. The fake needs no class and no mocking library, and the “before” version could not be tested this way. The cost is one more step for the reader, because to see which sender runs, you look at the caller. Modules 3 and 6 build on this idea.
Idea 3: combine objects instead of inheriting from them
Inheritance means a class gets its parent’s code with extends. It looks like reuse, but each combination of features needs its own class. Maya wanted logging around email notifications, so she wrote notify-before.ts:
import { MailClient } from "./fakes.ts";
class EmailNotifier {
protected mail = new MailClient("localhost");
async notify(to: string, text: string): Promise<void> {
await this.mail.send(to, text);
}
}
class LoggedEmailNotifier extends EmailNotifier {
override async notify(to: string, text: string): Promise<void> {
console.log(`[log] notify ${to}`);
await super.notify(to, text);
}
}
await new LoggedEmailNotifier().notify("ana@example.com", "Your tickets");
Output:
[log] notify ana@example.com
[mail] to ana@example.com: Your tickets
Then SMS arrives, and it needs logging too. With inheritance, that means SmsNotifier and LoggedSmsNotifier, and the logging code is written twice. Add retries, and you need a retrying version of each of the four classes.
Pause and predict: logging does not care whether the message goes by email or SMS. How could you write the logging once and put it around any sender?
Composition means you build behavior by putting one piece inside or around another while the program runs. Here is notify-after.ts:
import { MailClient } from "./fakes.ts";
type Notify = (to: string, text: string) => Promise<void>;
function withLogging(notify: Notify): Notify {
return async (to, text) => {
console.log(`[log] notify ${to}`);
await notify(to, text);
};
}
const mail = new MailClient("localhost");
const emailNotify: Notify = (to, text) => mail.send(to, text);
await withLogging(emailNotify)("ana@example.com", "Your tickets");
The output is the same two lines. withLogging takes any Notify function and returns a new one that logs first. So for SMS, you import SmsClient too and add three lines, with no new class. This excerpt shows the end of notify-after.ts after that change:
// Excerpt: the end of notify-after.ts with SMS added.
// The import now reads: import { MailClient, SmsClient } from "./fakes.ts";
const mail = new MailClient("localhost");
const sms = new SmsClient(process.env.SMS_KEY ?? "test-key"); // NEW
const emailNotify: Notify = (to, text) => mail.send(to, text);
const smsNotify: Notify = (to, text) => sms.send(to, text); // NEW
await withLogging(emailNotify)("ana@example.com", "Your tickets");
await withLogging(smsNotify)("+15550100", "Your tickets"); // NEW
Output:
[log] notify ana@example.com
[mail] to ana@example.com: Your tickets
[log] notify +15550100
[sms] to +15550100: Your tickets
Figure 6 compares the two designs with the same layout. The one difference is where logging lives. Inheritance copies it into each subclass, and composition writes it once as a wrapper.
Inheritance Composition
+--------------------------------+ +--------------------------------+
| [EmailNotifier] | | [emailNotify] |
| [LoggedEmailNotifier | | [smsNotify] NEW |
| extends EmailNotifier] | | |
| [SmsNotifier] NEW | | [withLogging] --> any Notify |
| [LoggedSmsNotifier | | logging written once |
| extends SmsNotifier] NEW | | |
+--------------------------------+ +--------------------------------+
Add retry: 4 more classes Add retry: 1 more function
Figure 6: with inheritance, logging is copied into each subclass; with composition, one wrapper serves every sender.
Inheritance is still useful when the subclasses share state and steps, and “Going deeper” shows that case. Keep such a class tree one level deep. withLogging is the GoF Decorator pattern in function form, and Module 3 teaches it in full.
Note: TypeScript’s
@decoratorsyntax is a different thing from the Decorator pattern. “Going deeper” shows the difference.
What TypeScript and Node.js change
The GoF book used C++ and Smalltalk, and some of its patterns work around limits of those languages. TypeScript and Node.js remove some of those limits. This section shows three features that make a pattern shorter or unnecessary.
Structural typing: the shape is the contract
TypeScript checks types by their shape, and this is called structural typing. An object fits an interface if it has the right properties and methods, whether or not its class says implements. In Java and C#, a class fits an interface only if it says implements. Save structural.ts:
interface PaymentProvider {
charge(amountCents: number): Promise<string>;
}
// No "implements" here, and it still fits PaymentProvider
class CardProvider {
async charge(amountCents: number): Promise<string> {
return `card charged ${amountCents} cents`;
}
}
// A plain object with the same shape also fits
const freeTickets = {
async charge(amountCents: number): Promise<string> {
return `free show, nothing charged (${amountCents} cents)`;
},
};
async function pay(provider: PaymentProvider, amountCents: number): Promise<void> {
console.log(await provider.charge(amountCents));
}
await pay(new CardProvider(), 2550);
await pay(freeTickets, 0);
Output:
card charged 2550 cents
free show, nothing charged (0 cents)
That’s why SmsClient fit TextSender in Idea 2, and why the test fake could be a plain object. You still write implements on a class when you want tsc to check the shape where the class is written, as the TypeScript handbook on type compatibility explains. So in later modules, any object or function of the right shape can fill a pattern’s interface.
Functions and closures as values
In TypeScript, a function is a value, so you can store it, pass it and return it. A closure is a function that remembers the variables around it when it was created. Save closures.ts:
type FormatPrice = (cents: number) => string;
// A factory function: it returns a new function that remembers `format`
function makePriceFormatter(currency: string): FormatPrice {
const format = new Intl.NumberFormat("en-US", { style: "currency", currency });
return (cents) => format.format(cents / 100);
}
const formatters: Record<string, FormatPrice> = {
US: makePriceFormatter("USD"),
DE: makePriceFormatter("EUR"),
};
for (const [country, formatPrice] of Object.entries(formatters)) {
console.log(country, formatPrice(1200));
}
Output:
US $12.00
DE €12.00
Intl.NumberFormat is built into JavaScript and formats numbers by language and currency. Each closure keeps its own format, where a class would keep it in a private field. withLogging from Idea 3 was a closure too.
So several patterns in Modules 2 and 4 often become one function. Write the function form first. Move to a class when the object needs a lifecycle, such as a connection to open and close.
Modules are created once
Node.js loads each module file once and keeps it in a cache. Every later import of the same file gets the same objects. Save seat-map-client.ts:
console.log("creating the seat-map client");
export const seatMapClient = {
baseUrl: "https://seats.tinytickets.example",
createdAt: new Date().toISOString(),
};
Then save singleton.ts:
// Two imports of the same file, as two route files would do
const first = await import("./seat-map-client.ts");
const second = await import("./seat-map-client.ts");
console.log("same object:", first.seatMapClient === second.seatMapClient);
Pause and predict:
singleton.tsimports the same file twice. How many times doescreating the seat-map clientprint, and issame objecttrue or false?
Output of npx tsx singleton.ts:
creating the seat-map client
same object: true
The top-level code ran once, and both imports got the same object. Node.js caches each ES module under its full file URL, as the ESM docs state.
A singleton is an object that the whole app shares, with only one instance. In TypeScript, an exported const often does that job, and Module 2 shows when that is enough. The cost shows up in tests, because a test can’t replace a module-level object without a mocking library. That’s the same trap as Figure 2.
How to read the figures in this course
Every module uses the same few figure types, built from the same parts as Figure 1. Boxes in square brackets are code, such as a module (file), a function or a class. A box marked (I) is an interface. People appear in round brackets, on the left.
There are three arrows and no others:
-->means “calls”...>means “implements”. The left side has the shape the interface on the right asks for, with or without theimplementskeyword.==>means “creates”. The left side runsnewor a factory function and gets the right side.
NEW marks what a change added.
A structure figure shows which code knows about which other code. Read each line from left to right as a sentence. Figure 7 is Figure 5 with each line read out.
[remind-main.ts] ==> [SmsClient]
"remind-main.ts creates an SmsClient"
[SmsClient] ..> [TextSender] (I)
"SmsClient has the shape TextSender asks for"
[remind-main.ts] --> [remindBuyer] --> [TextSender] (I)
"remind-main.ts calls remindBuyer, which calls a TextSender"
Figure 7: read each line of a structure figure as one sentence, left to right.
A good structure figure has few ==> arrows deep inside the code. Most creating should happen near the file that starts the app.
A request figure shows one HTTP request or one event in motion, as numbered steps from top to bottom. Each step is one call or one answer. A ~ await ~ line marks where the caller waits for a promise, and Node.js can serve other requests while it waits. Figure 8 follows one POST /checkout through Maya’s handler from Figure 1.
1 (Buyer) --> [handler] POST /checkout, 2 tickets
2 [handler] check input, find show, add fee: 2550
3 [handler] ==> [PayClient] new PayClient(PAY_KEY)
4 [handler] --> [PayClient] charge(2550)
~ await: the handler waits; Node.js serves other requests ~
5 [handler] ==> [MailClient] new MailClient(SMTP_HOST)
6 [handler] --> [MailClient] send(email, subject)
~ await ~
7 [handler] answers (Buyer) 201 {"id":1,"totalCents":2550}
Figure 8: one checkout request waits twice, and the buyer gets no answer until the email is sent.
Figure 8 shows a cost you could not see in the code. The payment finished at step 4, but the buyer still waits for the email service. Request figures exist to make that kind of fact visible.
What a pattern costs
Every pattern adds something you pay for each time you read or change the code:
- More files and names.
priceRulesis a new name. A full pattern can add an interface, two implementations and a factory, in four files. - Indirection. When
remindBuyercallssender.send, your editor’s “go to definition” lands on theTextSenderinterface, not on the code that runs. You must find out who created the sender. - Harder stack traces. A stack trace is the list of function calls Node.js prints with an error. Each wrapper, like
withLogging, adds a line to it. - Runtime cost. Every closure keeps its variables in memory as long as the closure lives. Every extra
asyncwrapper adds one more promise to wait for. These costs are small per call, and this course gives no numbers it has not measured. - Reading cost for the team. A pattern name helps only people who know it. A newcomer sees six files where they expected one function.
Pay these costs when the change they protect against happens. The next story shows what happens when it never does.
A story of too many patterns
Maya once read a pattern catalog on a weekend. On Monday, she rewrote sendReceipt, a 12-line function that sent one email through one service. The new version had an interface Notifier, an abstract class BaseNotifier, a class EmailNotifier, a NotifierFactory, a NotifierRegistry and a config file, in six files. Figure 9 shows both versions.
Before (12 lines) After (6 files)
[sendReceipt] ==> [MailClient] [NotifierFactory] --> [NotifierRegistry]
[NotifierFactory] ==> [EmailNotifier]
[EmailNotifier extends BaseNotifier]
[BaseNotifier] ..> [Notifier] (I)
[NotifierRegistry] --> [notifier.config]
Figure 9: six files for one email service that never changed.
A year later, TinyTickets still sent receipts through one email service. When Leo asked for the show date in the receipt, Maya edited four of the six files to pass one new field. The patterns protected against a second email service, which never came. They made the change that did come slower.
Write the plain function first. Add a pattern when a real change request touches the same code twice, or when you can’t test the code.
How to decide whether you need a pattern
Figure 10 is the first version of the decision figure that every module extends. It starts from the change in front of you, and its first exit is “no pattern needed”.
A change request arrives
|
v
Does it touch more than one place, or block a test? -- no --> No pattern
| yes needed.
v Edit the code.
Will this kind of change come again? -- no --> Make the edit; leave a note.
(new provider, new channel, new rule)
| yes
v
Can a function, an object map or a union absorb it? -- yes --> Use that.
| no
v
Look for a pattern (Modules 2 to 9): the change needs
state, a lifecycle, or many steps that vary.
Figure 10: most changes leave at the first three exits, and a pattern is the last step.
Check yourself
- In one sentence, what is a design pattern, and what is one cost it adds?
- Name the three common causes of hard-to-change Node.js code from this module.
- In Idea 1, what changed and what stayed the same in
totalCents? - Why can a plain object be passed where a function expects the
TextSenderinterface? - In a structure figure, what does
[a] ==> [b]mean, and why is it a warning sign when it appears deep inside business logic?
Answers
- A design pattern is a named answer to a design problem that keeps coming back. Any one of the five costs is correct: more files and names, indirection, harder stack traces, runtime cost, or reading cost for the team.
- Route handlers that do everything; clients created deep inside business logic; events and callbacks wired across files with no clear owner.
- The rule per ticket type changed often, so it moved into the
priceRulesobject map. The steps stayed the same: multiply price by quantity, apply the rule, add the booking fee. - TypeScript uses structural typing. An object fits an interface if it has the right properties and methods with the right types, with or without
implements. - It means
acreatesb, withnewor a factory function. Deep inside business logic, it means no caller can replaceb, so tests must use the realbor a mocking library (Figure 2).
Lab: add push reminders without touching the loop
Time: about 20 minutes. Put the files next to fakes.ts.
Here is TinyTickets’ reminder code, reminders.ts. It sends each buyer a reminder on the day of the show, by email or SMS:
import { MailClient, SmsClient } from "./fakes.ts";
export type Buyer = { name: string; channel: "email" | "sms"; contact: string };
export async function sendReminders(buyers: Buyer[], showTitle: string): Promise<number> {
let sent = 0;
for (const buyer of buyers) {
if (buyer.channel === "email") {
const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
await mail.send(buyer.contact, `Hi ${buyer.name}, ${showTitle} starts at 19:00 tonight.`);
sent++;
} else if (buyer.channel === "sms") {
const sms = new SmsClient(process.env.SMS_KEY ?? "test-key");
await sms.send(buyer.contact, `Hi ${buyer.name}, ${showTitle} starts at 19:00 tonight.`);
sent++;
}
}
return sent;
}
The change request: buyers who use the TinyTickets phone app want push notifications. A push buyer has channel: "push", and contact holds their device token. Use PushClient from fakes.ts.
Refactor reminders.ts so that this test file, reminders.test.ts, passes, and add the push channel:
import { test } from "node:test";
import assert from "node:assert/strict";
import { sendReminders, type Buyer, type Senders } from "./reminders.ts";
const buyers: Buyer[] = [
{ name: "Ana", channel: "email", contact: "ana@example.com" },
{ name: "Ben", channel: "sms", contact: "+15550101" },
{ name: "Chi", channel: "push", contact: "device-42" },
];
test("each buyer gets one reminder on their own channel", async () => {
const sent: string[] = [];
const senders: Senders = {
email: async (to, text) => { sent.push(`email ${to} | ${text}`); },
sms: async (to, text) => { sent.push(`sms ${to} | ${text}`); },
push: async (to, text) => { sent.push(`push ${to} | ${text}`); },
};
const count = await sendReminders(senders, buyers, "Songs of Spring");
assert.equal(count, 3);
assert.deepEqual(sent, [
"email ana@example.com | Hi Ana, Songs of Spring starts at 19:00 tonight.",
"sms +15550101 | Hi Ben, Songs of Spring starts at 19:00 tonight.",
"push device-42 | Hi Chi, Songs of Spring starts at 19:00 tonight.",
]);
});
Run it with npx tsx --test reminders.test.ts, and check types with npx tsc --noEmit. Then write run-reminders.ts, which creates the real clients and sends to one buyer on each channel.
Pause and predict: before you start, list what changes when a channel is added and what stays the same. Which of the three ideas will you use?
Hint 1
What changes is the list of channels and how each one sends. What stays the same is the loop, the message text and the count. The message text is also written twice today.
Hint 2
sendReminders should not create any client. Let it take the senders as its first parameter, as remindBuyer took a TextSender in Idea 2.
Hint 3
Write type Channel = "email" | "sms" | "push" and type Senders = Record<Channel, Send>, where Send is (to: string, text: string) => Promise<void>. Then senders[buyer.channel] picks the right function, and tsc fails if a channel has no sender.
Solution
reminders.ts:
export type Channel = "email" | "sms" | "push";
export type Buyer = { name: string; channel: Channel; contact: string };
export type Send = (to: string, text: string) => Promise<void>;
export type Senders = Record<Channel, Send>;
export async function sendReminders(
senders: Senders,
buyers: Buyer[],
showTitle: string,
): Promise<number> {
let sent = 0;
for (const buyer of buyers) {
const text = `Hi ${buyer.name}, ${showTitle} starts at 19:00 tonight.`;
await senders[buyer.channel](buyer.contact, text);
sent++;
}
return sent;
}
run-reminders.ts:
import { MailClient, PushClient, SmsClient } from "./fakes.ts";
import { sendReminders, type Senders } from "./reminders.ts";
// Each client is created once, here, and nowhere else
const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
const sms = new SmsClient(process.env.SMS_KEY ?? "test-key");
const push = new PushClient();
const senders: Senders = {
email: (to, text) => mail.send(to, text),
sms: (to, text) => sms.send(to, text),
push: (to, text) => push.send(to, text),
};
const count = await sendReminders(
senders,
[
{ name: "Ana", channel: "email", contact: "ana@example.com" },
{ name: "Ben", channel: "sms", contact: "+15550101" },
{ name: "Chi", channel: "push", contact: "device-42" },
],
"Songs of Spring",
);
console.log(`${count} reminders sent`);
Output of npx tsx run-reminders.ts:
[mail] to ana@example.com: Hi Ana, Songs of Spring starts at 19:00 tonight.
[sms] to +15550101: Hi Ben, Songs of Spring starts at 19:00 tonight.
[push] to device-42: Hi Chi, Songs of Spring starts at 19:00 tonight.
3 reminders sent
The test passes with ℹ pass 1 and ℹ fail 0. The solution uses all three ideas in small form:
- Idea 1. The channels that change moved into an object map.
- Idea 2.
sendRemindersdepends on theSendersshape, and the test fills it with plain functions. - Idea 3. Each sender is a small function you could wrap with
withLogginglater.
The old code also created a new client for every buyer, and now each client is created once.
The loop still sends one reminder at a time and stops at the first failure, as before. Sending in parallel and retrying failed sends are different changes, and Module 9 covers them.
Going deeper
You can skip this section. It covers details the main path left out.
Where the pattern idea came from
The idea came from the architect Christopher Alexander. His book A Pattern Language (1977) named solutions to building problems, such as where to put a window seat. The GoF book then sorted its 23 patterns into three groups:
- Creational patterns decide how objects get made (Module 2).
- Structural patterns decide how objects are put together and wrapped (Module 3).
- Behavioral patterns decide how objects share work and talk to each other (Modules 4 and 5).
Later authors added patterns outside the book, such as Repository (Module 7) and Circuit Breaker (Module 9), and this course names the source of each.
Discriminated unions: a closed list of cases
A payment can be paid, declined, or waiting for the buyer to confirm with their bank. A discriminated union holds such cases. It’s a union of object types that share one literal field, the tag, such as status: "paid" or status: "declined".
In a switch on the tag, TypeScript knows which object type each case has, so a field like reason exists only in the "declined" branch. You can also make tsc report an error when a new case has no branch, as the handbook shows under discriminated unions. So a switch on a union can replace some class-based patterns. Simple State and Command (Module 4) can start as a union.
Abstract classes: where inheritance still fits
CSV files of shows arrive from organizers, and every import follows the same steps. An abstract class is a class you can’t create with new, because it exists to be extended. It can mark some methods abstract, and each subclass must write those. Save abstract.ts:
type ShowRow = { title: string; date: string };
abstract class ShowImport {
// The steps that stay the same for every file format
async run(lines: string[]): Promise<void> {
let saved = 0;
for (const line of lines) {
const row = this.parse(line);
if (row === null) continue;
await this.save(row);
saved++;
}
console.log(`imported ${saved} of ${lines.length} lines`);
}
// The step that changes: each subclass must write it
protected abstract parse(line: string): ShowRow | null;
protected async save(row: ShowRow): Promise<void> {
console.log(`saved ${row.title} on ${row.date}`);
}
}
class CommaImport extends ShowImport {
protected parse(line: string): ShowRow | null {
const [title, date] = line.split(",");
return title && date ? { title, date } : null;
}
}
await new CommaImport().run(["Songs of Spring,2027-03-14", "a broken line"]);
Output:
saved Songs of Spring on 2027-03-14
imported 1 of 2 lines
protected means only the class and its subclasses can call the method. See abstract classes in the handbook.
This is Template Method (Module 4) in its class form. A function that takes parse as a parameter does the same job in fewer lines. The class is worth its extra lines when the steps share state, or when a framework expects you to extend its class.
Decorator syntax is not the Decorator pattern
A TypeScript decorator is a function that you attach with @name to a class or a class member, and that can replace or change it. The Decorator pattern wraps an object to add behavior. The syntax is a language feature, and it can wrap a method, register a route, or do something that isn’t wrapping at all.
This course uses the standard decorators that TypeScript 5.0 added, which the TypeScript 5.0 release notes explain. Node.js can’t run decorator syntax on its own yet, so a file that uses it needs tsx or tsc. Use the syntax when you own the class and want the wrapper visible at the method. The function form from Idea 3 works on anything, classes or not.
NestJS, a framework for Node.js servers, uses an older decorator format. Its projects turn on the experimentalDecorators setting, as the NestJS starter tsconfig does. So when you read NestJS code in Module 6, the @ looks the same, but the decorator functions have a different signature.
When a module is loaded twice
The module cache has a limit. Two copies of one package in different node_modules folders have two file URLs, so you get two objects, as the Node.js docs on module caching caveats describe.
Cheat sheet
| Idea or tool | The problem it answers | The signal in your code |
|---|---|---|
| Separate what changes | One kind of edit keeps hitting the same function | An if or switch that grows with every request |
| Depend on an interface | A test cannot replace a client | new SomeClient(...) inside business logic |
| Combine, do not inherit | Each feature mix needs a new class | Class names like LoggedRetryingEmailNotifier |
| Structural typing | Fakes need a mocking library | Test files full of module mocks |
| Function or closure | A class with one method and no lifecycle | class X { run() {} } used in one place |
| Module caching | Need exactly one shared object | A getInstance() method in TypeScript |
| No pattern | The change is a one-time edit | Only one place to change, and it is easy to test |
Figure 11 shows the three ideas, each with the code that used it.
1 Separate what changes [totalCents] --> [priceRules]
steps stay rules change
2 Depend on an interface [remindBuyer] --> [TextSender] (I)
[SmsClient] ..> [TextSender] (I)
3 Combine, do not inherit [withLogging] --> [emailNotify]
[withLogging] --> [smsNotify]
Before any of them: is a pattern needed at all? (Figure 10)
Figure 11: three ideas, one line of TinyTickets code for each.
- Three causes: a route handler that does every job, a client created deep in business logic, and events with no owner.
- Idea 1: move the part that keeps changing into its own place, often an object map.
- Idea 2: let the caller pass in the client through an interface, so a test can pass in a plain object.
- Idea 3: wrap small functions instead of writing a subclass for each mix of features.
- Costs: every pattern adds files, jumps and reading time, so write the plain function first.
Next, Module 2 starts from the new PayClient(...) in Maya’s handler. It asks who should create objects, and when a factory function or a cached module is the right answer.
Sources
- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994. The pattern names, the three groups and “favor object composition over class inheritance”.
- Christopher Alexander and others, A Pattern Language, Oxford University Press, 1977. The origin of the pattern idea.
- TypeScript handbook: type compatibility, narrowing and discriminated unions, classes and abstract members, utility types (
Record), TypeScript 5.0 decorators. - Node.js documentation: events, test runner, assert, ES modules, module caching caveats.
- NestJS: typescript-starter
tsconfig.json. - tsx: tsx.is.