Which Pattern When — Design Patterns

Choose a pattern from its pain, the problem that appears in the code. Write simple code, wait for the pain to appear (usually at the second change), name it…

Choosing a pattern is like taking medicine from a first-aid box: you name the symptom first, then take the medicine that treats that symptom. You don't take cough syrup only because it's in the box. And for many complaints the answer isn't medicine at all, only rest. Code works the same way. The symptom is a pain, a problem in the code that appears when the app changes. The medicine is a pattern, the first-aid box is every pattern you've learned, and rest is simple code with no pattern. Each pattern treats one particular pain, and when the pain isn't there, the pattern only adds code.

Start from the pain, not from the pattern

The safe order:

  1. Write the simplest code that works.
  2. Wait for the pain to appear. It usually appears at the second change: the second delivery service, the second party that needs telling, the second file copying the same code.
  3. Name the pain in one sentence: "every new delivery service means changing three files".
  4. Pick the pattern that treats that pain.
  5. Check the result: is the code easier to read and change? If not, undo the change.

The principle behind step 2 has a name: YAGNI (You Aren't Gonna Need It). It means: don't build something for a need that isn't here yet.

The map: Kancil Courier's pains and their cures

Every earlier lesson followed that order. Here is the pain each lesson covered, and the pattern that treated it. The right column starts with the lesson's title:

pain at Kancil Courier pattern
lastTrackingNo can be overwritten by another file Module Pattern: a private variable in a closure or an ES module
updateStatus changes every time a new party needs telling Observer Pattern: tracker.on("status", fn)
two tracking counters, two KCL-0001 Singleton Pattern: one trackingCounter
an if per delivery service copied into checkout, admin and the API Factory Pattern: createShipment and SERVICES
a Merpati sticker tracked in Jalak's system Abstract Factory Pattern: one partnerKit per partner
new Shipment(...) with 8 arguments in a row Builder Pattern: ShipmentBuilder
a pricing switch that keeps growing Strategy Pattern: PRICING[service](kg)
insurance, wooden crate and discounts as flags Decorator Pattern: withInsurance(calculateShipping) (shortened, without the item value)
partner data arriving as { awb, weightGrams } Adapter Pattern: adaptMerpati
the token check, the request limit and validation in one handler Middleware / Chain of Responsibility: auth → rateLimit → validate → createShipment
status changes must be undoable (can be cancelled) Command Pattern: changeStatus with do and undo
the warehouse has to know every receiver of news Pub/Sub Pattern: a broker and topics
four sending steps copied in three places Facade Pattern: KancilCourier.send
data, rules and display mixed in a click listener MVC / MVVM
api.get and filtering on every page, tests need a server Repository Pattern

Read the table from the left: the pain first. If your code doesn't have a pain from the left column, the pattern on the right isn't needed yet.

When the answer is: no pattern

Here are two ways to turn a number into a tracking number, with a Singleton and with a plain function:

// A Singleton for something that stores nothing
class TrackingFormatter {
  static instance = null
  static getInstance() {
    if (!TrackingFormatter.instance) TrackingFormatter.instance = new TrackingFormatter()
    return TrackingFormatter.instance
  }
  format(n) {
    return "KCL-" + String(n).padStart(4, "0")
  }
}
console.log(TrackingFormatter.getInstance().format(7)) // KCL-0007

// A plain function: the same result, no layer
function formatTrackingNo(n) {
  return "KCL-" + String(n).padStart(4, "0")
}
console.log(formatTrackingNo(7)) // KCL-0007

In the Singleton Pattern lesson, Singleton treats trackingCounter, because trackingCounter stores a count that must exist only once. formatTrackingNo stores nothing: a number goes in, text comes out. There's no state (data that is kept and can change) to keep single, so the Singleton here treats nothing. A plain function is enough.

Two more examples from this track:

Patterns that look alike, with different intent

Some patterns look alike in code, so choose by intent, meaning the pain you want to treat, not by the shape of the code.

Notifications: Strategy or Observer? Kancil Courier can send news by email, SMS and push notification (a notification that appears on the phone screen). The key question: is each message sent through the one channel the customer picked, or through every channel? Here is the one-channel version. SEND[p.channel] takes one function from the SEND object, the one for the channel the customer picked:

// The customer picks ONE channel: Strategy, chosen while the program runs
const SEND = {
  sms: (p) => console.log("SMS to " + p.name + ": " + p.trackingNo + " " + p.status),
  email: (p) => console.log("Email to " + p.name + ": " + p.trackingNo + " " + p.status),
  push: (p) => console.log("Push to " + p.name + ": " + p.trackingNo + " " + p.status),
}

function notify(p) {
  SEND[p.channel](p)
}

notify({ name: "Rina", channel: "email", trackingNo: "KCL-0001", status: "delivering" })
// Email to Rina: KCL-0001 delivering

If those three functions were registered as Observer listeners (tracker.on("status", ...) three times), one status change would send three messages. Rina would then get an SMS and a push she never chose. The rule: one picked out of several is Strategy. Everyone registered gets told is Observer.

One database connection: Singleton. A database connection is expensive to create, and the database limits how many it accepts (MySQL takes 151 by default). If every query opens a new connection, three queries open three connections, and on a busy day the database starts refusing. Create the connection, or one connection pool (a set of connections used in turn), once, then use it across the whole app. In JavaScript, an object exported from a module is already a singleton. Laravel does it in its Service Container, the place where Laravel makes and keeps objects. $this->app->singleton('db', ...) gives every part of the app the same database manager (the Laravel object that manages database connections) for the whole request.

Other look-alike pairs worth telling apart:

⚠️ Picking the wrong medicine

TL;DR: Choose a pattern from its pain, the problem that appears in the code. Write simple code, wait for the pain to appear (usually at the second change), name it in one sentence, then take the pattern that treats that pain. Examples from this track: an if per delivery service copied everywhere → Factory, a new party to tell → Observer, two tracking counters → Singleton, and so on. Often the answer is no pattern (YAGNI, "You Aren't Gonna Need It"). The function formatTrackingNo stores no state (data that can change), so a plain function is enough, with no Singleton. Rates that only differ in numbers also only need a data table, with no Strategy. Look-alike patterns are told apart by intent: news through the one channel the customer picked is Strategy, and news to every channel is Observer. A database connection created once and used across the whole app is a Singleton (in JavaScript, a module is enough).

⚡ Start from the pain

Meaning: A pain is a problem in the code that appears when the app changes. Write the simplest code first, wait for the pain to appear (usually at the second change), then name it in one sentence ("every new delivery service means changing three files"). Only then pick the pattern that treats that pain. This principle is called YAGNI (You Aren't Gonna Need It): don't build something for a need that isn't here yet.

⚡ Sometimes the answer is: no pattern

Write:

function formatTrackingNo(n) {
  return "KCL-" + String(n).padStart(4, "0")
}

Meaning: formatTrackingNo turns a number into a tracking number. This function stores no state (data that is kept and can change): a number goes in, text comes out. A Singleton for this function treats nothing, because there's nothing to keep single. A plain function is enough. Rates that only differ in their numbers also only need a data table, with no Strategy.

⚡ Choose by intent

Guess first: a database connection must be created once, then used across the whole app. Which pattern fits?

Singleton. A connection is expensive to create, and the database limits how many it accepts, so create it once. In JavaScript, an object exported from a module is already a singleton.

Meaning: Patterns whose code looks alike are told apart by intent, meaning the pain you want to treat. For notifications by email, SMS or push, one picked out of several (the one channel the customer picked) is Strategy, and everyone registered gets told (every channel) is Observer.

What you will learn