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
- A decorator is a function that takes a function and returns a new function. A function that takes or returns a function is called a higher-order function.
- The new function is called the same way,
("express", 2), and returns a number like the original. The caller doesn't know there are layers. ...argsin the parameters gathers every argument into an array["express", 2].fn(...args)spreads them back into the original as they were. So the same decorator fits a function with any number of arguments.calculateShippingisn't touched. Callers that need no extras keep using the original.- The same shape works for objects. The wrapper object has the same methods as the original object: each method adds something, then passes the call on to the original object. That's why a decorator is often described as adding behaviour to an object while the program runs, without changing its original class.
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
fn.nameis the original function's name. Every function written asfunction calculateShipping(...)has a.nameholding"calculateShipping".return resultpasses the original result on. Without that line, the logging layer turns every price intoundefined.console.logwith several arguments prints them all separated by a space:console.log("Calling with", [2, 3])printsCalling with [2, 3](Node writes it as[ 2, 3 ]).
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 first line, with the discount on the outer layer: (36 + 15) × 0.9 = 45.9. The discount also cuts the crate's cost.
- The second line, with the discount on the inner layer: 36 × 0.9 + 15 = 47.4. The crate is paid in full.
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:
- Before calling
fn, print"Calling " + fn.name. - Call
fn(...args)and keep the result. - After that, print
"Result: " + result. - Return the result, so
console.log(loggedAdd(3, 4))prints7.
The console then has six lines: Calling add, Result: 7, 7, Calling multiply, Result: 30, 30.
When you don't need a decorator
- The core behaviour itself changes. Express goes up to $20/kg? Change
PRICING, don't wrap it in a correcting layer. - The extra is only used once. Write it in that one place.
- The stack gets too deep. Five layers means five places to check when the price is wrong, plus an order hidden inside the stack.
⚠️ Layers that quietly change the result
- Forgetting
return. The layer returnsundefined. In the exercise,console.log(loggedAdd(3, 4))then printsundefined, not7. - Calling
fn()without...args. The original is called with no arguments. In the exercise,add()with no arguments givesNaN. - Wrapping another layer and then reading
fn.name. The function a decorator returns has no name, sowithLogging(withWoodenCrate(calculateShipping))records an empty name. - An order nobody meant. Swapping two layers can change the price with no error.
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.