Decorator Pattern — Design Patterns

A decorator is a wrapping function (a wrapper): a function that takes a function and returns a new function called the same way. The new function adds…

How do you add the cost of a wooden crate to the shipping price without touching calculateShipping (the function that calculates the shipping cost, from the Strategy Pattern lesson) at all? You wrap it.

The Decorator pattern wraps a function (or an object) in a new function that's called the same way. The new function adds something before or after the original is called, without changing the original. This wrapping function is called a decorator, or a wrapper. Picture a parcel wrapped in layers. The box with the goods stays the same, but you can add layers outside it: bubble wrap, a wooden crate, an insurance sticker. Each layer adds something, the contents stay the same, and the parcel is still sent the same way. Layers can be added or removed as the customer asks. In code, the box with the goods is the original function, and each layer is one decorator put around it.

The problem: a core function that keeps gaining flags

calculateShipping is used by the checkout page, the admin page and the API. Every extra cost gets added inside it as a flag (a parameter that switches one extra on or off):

function calculateShipping(service, kg, insurance, itemValue, woodenCrate, log) {
  let price = PRICING[service](kg)
  if (insurance) price = price + itemValue * 0.005
  if (woodenCrate) price = price + 15
  if (log) console.log("shipping " + price)
  return price
}

Every addition opens the function that every part of the app uses, and every caller gets new parameters. The other way is to copy the function per combination (calculateShippingWithInsurance, calculateShippingWithCrate, calculateShippingWithInsuranceAndCrate, ...). That way is worse: 3 extras means 2 × 2 × 2 = 8 copies.

The decorator: a function that wraps a function

In the decorator version, calculateShipping only calculates the rate. Each extra is a separate function that wraps it:

const PRICING = { regular: (kg) => kg * 10, express: (kg) => kg * 18 }

function calculateShipping(service, kg) {
  return PRICING[service](kg)
}

function withInsurance(fn, itemValue) {
  return function (...args) {
    return fn(...args) + itemValue * 0.005
  }
}

function withWoodenCrate(fn) {
  return function (...args) {
    return fn(...args) + 15
  }
}

const shipping = withWoodenCrate(withInsurance(calculateShipping, 2000))
console.log(calculateShipping("express", 2)) // 36, the original is unchanged
console.log(shipping("express", 2))          // 61

This is how shipping("express", 2) runs. The innermost layer is calculateShipping, and its result goes up to the layer outside it:

layer receives returns
calculateShipping ("express", 2) 36
withInsurance 36 36 + 2000 × 0.005 = 46
withWoodenCrate 46 46 + 15 = 61

A decorator that records calls

A layer doesn't have to change the number. A layer can also add behaviour, for example recording every call:

function withLogging(fn) {
  return function (...args) {
    const result = fn(...args)
    console.log(fn.name + "(" + args.join(", ") + ") = " + result)
    return result
  }
}

withLogging(calculateShipping)("express", 2) // calculateShipping(express, 2) = 36

The order of the layers changes the price

Express shipping for 2 kg is $36. The wooden crate adds $15, and the promo takes 10% off. Before you look at the result, take a guess: if the order of the two layers is swapped, is the price the same or different? The promo layer is called withDiscount:

function withDiscount(fn) {
  return function (...args) {
    return fn(...args) * 0.9
  }
}

console.log(withDiscount(withWoodenCrate(calculateShipping))("express", 2)) // 45.9
console.log(withWoodenCrate(withDiscount(calculateShipping))("express", 2)) // 47.4

The results are not the same: a gap of $1.50. The order of the layers is a business rule, which means a rule that comes from how the business works, like "does the promo apply to the crate?". Write the stack of layers in one place with a clear name, and don't put it together again in every file.

You'll meet the same shape again in the Middleware / Chain of Responsibility lesson. The @name syntax above a class or method (in TypeScript and Angular) is also called a decorator. The idea is similar, since both wrap, but it's a feature of the programming language, separate from this pattern, and it isn't needed here.

The exercise: withLogging

In the exercise, you use the logging layer's shape, with another format. The starter already holds add(a, b), multiply(a, b) and their calls, for example through loggedAdd, which is add wrapped in withLogging. You write withLogging(fn), which returns a new function. That new function works like this:

  1. Before calling fn, print "Calling " + fn.name.
  2. Call fn(...args) and keep the result.
  3. After that, print "Result: " + result.
  4. Return the result, so console.log(loggedAdd(3, 4)) prints 7.

The console then has six lines: Calling add, Result: 7, 7, Calling multiply, Result: 30, 30.

When you don't need a decorator

⚠️ Layers that quietly change the result

TL;DR: A decorator is a wrapping function (a wrapper): a function that takes a function and returns a new function called the same way. The new function adds something before or after calling the original (fn(...args)), then returns its result. The original isn't changed, and layers (decorators put around a function) are added as needed: withWoodenCrate(withInsurance(calculateShipping, 2000)) turns a shipping cost of 36 into 61. The order of the layers can change the result: a 10% discount outside the wooden crate layer gives 45.9, inside it 47.4. So write the stack of layers in one place. For the exercise: print "Calling " + fn.name, call fn(...args), print "Result: " + result, then return the result.

⚡ A function that wraps a function

Write:

function withWoodenCrate(fn) {
  return function (...args) {
    return fn(...args) + 15
  }
}

Meaning: This is a decorator: a wrapping function (a wrapper) that takes a function fn and returns a new function that's called the same way. A decorator adds something before or after the original is called, without changing the original. Here, the new function calls the original, then adds 15 for the wooden crate. ...args passes every argument on as it was.

⚡ Layer on layer

Write:

const shipping = withWoodenCrate(withInsurance(calculateShipping, 2000))
console.log(calculateShipping("express", 2)) // 36, the original is unchanged
console.log(shipping("express", 2))          // 61

Meaning: calculateShipping calculates the basic shipping cost. withInsurance is another decorator: a layer that adds an insurance cost for goods worth 2000. So shipping is calculateShipping wrapped in two layers, and 36 becomes 61 (plus 10 for insurance and 15 for the wooden crate). The caller doesn't know there are layers, and the original function doesn't change. If one layer forgets return, the price becomes undefined.

⚡ The order of the layers changes the price

Write:

console.log(withDiscount(withWoodenCrate(calculateShipping))("express", 2))
console.log(withWoodenCrate(withDiscount(calculateShipping))("express", 2))
Guess first: withDiscount takes 10% off, and withWoodenCrate adds $15. The second line puts those two layers on in the opposite order from the first line, on top of a shipping cost of 36. Same price or different?

Different: 45.9 and 47.4. A discount on the outer layer (the first line) also cuts the crate's cost, one on the inner layer doesn't.

Meaning: The order of the layers is a business rule: a rule that comes from how the business works, for example whether the promo applies to the crate. Write the stack of layers in one place with a clear name.

What you will learn