What Is a Design Pattern? — Design Patterns

A design pattern is a general, reusable solution to a code design problem (a problem in how code is organised) that appears often. A design pattern is a…

A tailor doesn't draw a shirt collar from nothing for every customer. The tailor has a paper pattern for the collar. That pattern is used again for every customer, and only the size and the fabric are adjusted. The pattern is not the shirt: it only shows the shape of the collar to make.

Code has patterns too. They are called design patterns: each is a way to solve one code design problem that appears often. Code design means how code is organised, for example which parts exist and which part calls which. Each pattern has a name and has been tested in many projects. As with the tailor, a design pattern is the paper pattern: the shape of the solution. The code you write is the shirt, and that code is different in every project.

The example for the whole track: Kancil Courier

Throughout this track we maintain one app: Kancil Courier, a small parcel courier. The app does three things:

Its first version was written fast, all in one file. It has four functions: nextTrackingNo makes the next tracking number, price calculates the shipping cost, eta gives the estimated arrival time, and updateStatus changes a parcel's status and then tells the customer:

var lastTrackingNo = 0 // any file can read and change it

function nextTrackingNo() {
  lastTrackingNo = lastTrackingNo + 1
  return "KCL-" + String(lastTrackingNo).padStart(4, "0")
}

function price(service, kg) {
  if (service === "regular") return kg * 10
  if (service === "express") return kg * 18
}

function eta(service) {
  if (service === "regular") return "3 days"
  if (service === "express") return "1 day"
}

function updateStatus(parcel, status) {
  parcel.status = status
  sendSms(parcel)        // every new party that needs to hear about it...
  refreshTracking(parcel) // ...means one more line here
}

The code works. The problems only appear when the app changes:

In this track, we call problems like these three a pain. Each later lesson takes one pain and cures it with one pattern.

A pattern is a shape, not a snippet

A pattern has four parts: a name, the problem it solves, the shape of the solution, and its cost. The cost of a pattern: the code gets more parts and more names. Take the Observer pattern. The shape of its solution: "tell everyone who signed up when something happens". In the browser, the code is button.addEventListener("click", fn): the function fn signs up, then it is called every time the button is clicked. In Node.js (JavaScript that runs outside the browser), the code is emitter.on("data", fn): fn is called every time new data arrives. The code differs, the pattern is the same.

Because it has a name, a pattern also becomes a shared word in a team. Saying "parcel status uses Observer" is faster than explaining, one by one, the functions that are called.

Three groups of patterns

The book Design Patterns (1994) was written by four authors nicknamed the Gang of Four. The book collected 23 patterns and split them into three groups by the problem they solve. An object here is a value that holds data and functions.

Group The problem Example patterns The pain in Kancil Courier
Creational how objects are made Factory, Singleton, Builder a new service must be added to price and eta
Structural how objects are put together and connected Adapter, Decorator, Facade the partner courier's data uses other field (property) names
Behavioral how objects tell each other things and share work Observer, Strategy, Command updateStatus changes for every new party

An example of a creational pain is in the first Kancil Courier code. Say a new sameday service ($25 per kg) is added to price only, and forgotten in eta. Then the shipping cost and the estimated time for a 2 kg sameday parcel are printed:

console.log("sameday:", price("sameday", 2), "dollars,", eta("sameday"))
// sameday: 50 dollars, undefined

price already has a line for sameday, but eta doesn't. Inside eta("sameday"), no if matches, so the function ends without a return and gives undefined. There is no error message, only a hole in the data. The Factory pattern cures it by putting everything about one service in one place:

const SERVICES = {
  regular: { perKg: 10, eta: "3 days" },
  express: { perKg: 18, eta: "1 day" },
  sameday: { perKg: 25, eta: "today" }, // a new service: one line
}

function createShipment(service, kg) {
  const s = SERVICES[service]
  return { service, price: kg * s.perKg, eta: s.eta }
}

const p = createShipment("sameday", 2)
console.log("sameday:", p.price, "dollars,", p.eta) // sameday: 50 dollars, today

This track also has the Module pattern, the most basic way in JavaScript to hide data (like lastTrackingNo) from other files. The Module pattern isn't in the three groups above because it isn't in the book Design Patterns. But in JavaScript, the Module pattern is the base for the other patterns.

Start from the problem

A pattern works like medicine: use it when the pain is really there. Say Kancil Courier has only one service and no plan to add more. Then createShipment and SERVICES only add names to remember and another place to open when reading the code, and they cure nothing. Write the simple version first. When the same change starts to repeat (a second service, a third), change the code to the pattern that fits.

The order is always the same: name the problem first ("a new service has to be added in two places"), then look for the pattern that solves that problem.

⚠️ When does a pattern turn into a burden?

TL;DR: A design pattern is a general, reusable solution to a code design problem (a problem in how code is organised) that appears often. A design pattern is a shape, not a ready-to-paste snippet: each pattern has a name, a problem it solves, a solution shape and a cost (the code gets more parts). There are three groups of patterns. Creational is about how objects (values that hold data and functions) are made: Factory, Singleton, Builder. Structural is about how objects are put together: Adapter, Decorator, Facade. Behavioral is about how objects tell each other things: Observer, Strategy, Command. The example for this whole track is Kancil Courier, a parcel courier app. Start from the problem, not the pattern: if no problem goes away, don't use a pattern.

⚡ A pattern is a shape, not code

Guess first: a design pattern is the shape of a solution, and it has a name. The browser has button.addEventListener("click", fn), Node.js (JavaScript outside the browser) has emitter.on("data", fn). Both mean "call fn when something happens". Same pattern or different?

The same. The pattern's name is Observer: "tell everyone who signed up when something happens". The code differs, the pattern is the same.

Meaning: A design pattern is a general, reusable solution to a code design problem (a problem in how code is organised) that appears often. Each pattern has a name, a problem it solves, a solution shape and a cost: the code gets more parts. A pattern isn't ready-to-paste code.

⚡ One service, two places

Write:

console.log("sameday:", price("sameday", 2), "dollars,", eta("sameday"))
Guess first: a courier app has two functions. price calculates the shipping cost, eta gives the estimated arrival time. A new sameday service ($25 per kg) was added to price but forgotten in eta. What gets printed for a 2 kg parcel?

sameday: 50 dollars, undefined. eta has no line for sameday yet, so it gives undefined. There is no error message, only a hole in the data.

Meaning: One service has to be written in two places, and one of them was forgotten. This problem belongs to the Creational group: patterns about how objects (values that hold data and functions) are made, such as Factory, Singleton, Builder. The other two groups of patterns are Structural (how objects are put together) and Behavioral (how objects tell each other things).

⚡ One service, one place

Write:

const SERVICES = {
  regular: { perKg: 10, eta: "3 days" },
  express: { perKg: 18, eta: "1 day" },
  sameday: { perKg: 25, eta: "today" }, // a new service: one line
}

function createShipment(service, kg) {
  const s = SERVICES[service]
  return { service, price: kg * s.perKg, eta: s.eta }
}

Meaning: This is the Factory pattern: createShipment is the only place where a shipment object is made. In SERVICES, each service's rate per kg and estimated time are on one line. So it's hard to add a service's rate and forget its estimated time.

⚡ Start from the problem

Meaning: A pattern works like medicine: use it when the pain, which is a problem in your code, is really there. Name the problem first ("a new service has to be added in two places"), then look for the pattern. If no problem goes away, don't use a pattern.

What you will learn