Decorator: adding behaviour by wrapping

  • Lesson 13 of 32
  • 11 min
  • Intermediate
  • 12 steps

Adding logging and caching to an HTTP client with inheritance takes one subclass per mix. You will wrap it in layers with the same interface and see why the order of those layers changes the result.

Extra classes to combine
2
Log lines (example)
—
AppwithCacheBufferedReader@lru_cachewithCachewithLogInputStreamReaderwithLogHttpSystem.infibHttpAPIAPIFetcherinterfaceFetcherLoggedHttpLoggedHttpCachedHttpCachedHttpCachedLoggedHttpCachedLoggedHttpRetryHttpRetryHttpbase classboth at once · one more classInheritance for every mixclass Http { get(url) { … } }class LoggedHttp extends Http {}class CachedHttp extends Http {}class CachedLoggedHttp extends Http {}new behaviour7 subclasses to maintainSubclasses for 3 behavioursjust one3two together3all three1total7log + delegatethe same interfaceOne contract for bothinterface Fetcher {get(url: string): Promise<string>;}class Http implements Fetcher {async get(url: string) { … }}console.log hereunchangedwithLogfunction withLog(f: Fetcher): Fetcher {return {get(url) {+console.log("GET", url);▸return f.get(url);},};}not there · passes it on1 log lineOne layer inside anotherconst http = new Http();▸const client = withCache(withLog(http));await client.get("/a"); // reaches Httpawait client.get("/a"); // the cache answershas it · answersno new logwithCachefunction withCache(f: Fetcher): Fetcher {const cache = new Map();return { async get(url) {▸if (!cache.has(url))cache.set(url, await f.get(url));return cache.get(url);} };}logs both callscache hitSame pieces, another order−const client = withCache(withLog(http));+const client = withLog(withCache(http));adds a bufferbytes → charactersJava: a Reader inside anotherBufferedReader in = new BufferedReader(new InputStreamReader(System.in));▸String line = in.readLine();memoises fib(n)the original functionPython: wrapping a functionfrom functools import lru_cache▸@lru_cache(maxsize=None)def fib(n):if n < 2: return nreturn fib(n - 1) + fib(n - 2)one interfaceThree wrong ideas“order does not matter”it changes what gets logged“it is the @ syntax”it is an object that wraps“it can change the interface”then it is an adapterfails 3 layers downclient is another objectWhat you see when debugging▸client === http; // false// network error, outside in:withCache → get(url)withLog → get(url)Http → get(url)▸fetch(url) // fails herewraps and delegatesDecorator in a tableproblema subclass per mixsolutionwrap and delegatecontractthe same interfacewatchthe order of the layersskip itfor one fixed mix
  • request
  • response
  • cache miss
  • failed request

Step 1 of 12

Problem

One subclass for every mix

You have an Http class with a get(url) method that downloads a page. One day you are asked to log every call; another day, to cache repeated responses.

With inheritance, every mix is a subclass: LoggedHttp, CachedHttp and, to get both, CachedLoggedHttp. Two behaviours already take three classes, and the third repeats code from the other two.

What changed

  • LoggedHttp, CachedHttp and CachedLoggedHttp

Step 2 of 12

Problem

A third behaviour arrives

Now you also want to retry when the network fails: RetryHttp is born. But you also want caching with retries, logging with retries and all three together.

With 3 behaviours you can combine, you get 7 subclasses (2³ − 1), as the panel adds up; with 4 it would be 15. Every new behaviour almost doubles the classes, and each one fixes the order in which they apply.

What changed

  • RetryHttp
  • 3 more combinations with retries

Step 3 of 12

Concept

Wrap instead of inherit

Another idea: an object that wraps another. withLog takes a Fetcher, returns another Fetcher and, in its get, writes the log and then passes the call to the object inside.

Both keep the same contract, the Fetcher interface. That is why App cannot tell the difference: it calls get(url) as always. That is a Decorator: the same interface, extra behaviour, and the original class untouched.

What changed

  • interface Fetcher
  • withLog
  • the subclasses

Step 4 of 12

Technique

A decorator in a few lines

The decorator keeps the object inside (f), does its part and delegates with f.get(url). Here it is written as a function that returns an object; a class with a private field works the same.

Notice what did not happen: Http did not change and there are no subclasses. Any Fetcher can be wrapped: the real one, a fake one for tests or another decorator.

What changed

  • console.log before delegating
  • Http, unchanged

Step 5 of 12

Solution

One decorator inside another

Since a decorator is also a Fetcher, it can be wrapped again: withCache(withLog(http)). The first call to /a enters through the cache, which does not have it yet (a cache miss), goes through the log and reaches Http.

The response comes back through the same layers and the cache keeps it on the way. Each behaviour is one class: with caching, logging and retries you would have 3 decorators, not 7 subclasses.

What changed

  • withCache, outside withLog

Step 6 of 12

Solution

The second call does not go down

Second call to /a: the cache already has the response and returns it without calling the object inside. withLog and Http never notice: no second log line and no second request to the API.

The line that decides is the if: only when the URL is not in the Map does withCache delegate to f.get(url).

What changed

  • the cache answers on its own

Step 7 of 12

Problem

The order of the layers does matter

Swap the order: withLog(withCache(http)). Now the log sits outside the cache, so it sees both calls, including the one the cache answers on its own. Same pieces, 2 log lines instead of 1.

Neither order is wrong: it depends on what you want to record. But the result changes, so the order is part of the design. Build the chain in one place so it does not depend on who writes it.

What changed

  • withLog outside, withCache inside

Step 8 of 12

Concept

You already use it: reading files in Java

Java's input and output library is built this way. BufferedReader is a Reader that wraps another Reader and adds a buffer, which lets you read line by line with readLine(). The InputStreamReader documentation recommends exactly this: wrapping it in a BufferedReader.

InputStreamReader, in turn, turns the bytes of an InputStream into characters. That changes the interface, so it acts as an adapter (you saw it two lessons ago). Both patterns can live in the same chain.

What changed

  • withCache → BufferedReader
  • withLog → InputStreamReader

Step 9 of 12

Concept

You already use it: `@lru_cache` in Python

In Python, functools.lru_cache wraps a function with another one that memoises its results: if it already computed fib(30), it returns it without computing it again. It is the idea of withCache, applied to a function.

The @ is language sugar: putting @lru_cache(maxsize=None) above def fib is the same as writing fib = lru_cache(maxsize=None)(fib) below it. And functools.wraps copies the original function's name and docs onto the wrapper, so it still looks like it.

What changed

  • withCache → @lru_cache
  • Http → fib

Step 10 of 12

Concept

Three wrong ideas

“Order does not matter”: you saw it does. With the log outside the cache, every call leaves a line.

“Decorator is the `@` syntax”: the @ in Python, or in TypeScript (which since version 5.0 follows the standard JavaScript proposal), is a language feature related to the pattern, not the pattern. withLog is a Decorator and has no @.

“A decorator can change the interface”: if it does, you can no longer use it in place of the original. That is an adapter.

Step 11 of 12

Trade-off

When not to wrap, and what it costs

If you always use the same combination and it never changes, write that class and move on: a decorator “just in case” is one more layer to read. The pattern pays off when you combine behaviours in different ways or switch them on from configuration.

Costs: each layer is one more step in an error's trace, and with many layers it is hard to see where it failed. Also, the wrapper is another object: client === http is false, and so is client instanceof Http. Do not compare identities through a decorator.

Step 12 of 12

Summary

Wrap to add

When you want to add behaviour (logging, caching, retries) to an object without touching its class or creating a subclass per mix, wrap it in another with the same interface that does its part and delegates.

Decorators stack in the order you choose, and that order changes the result. If the combination is always the same, you do not need one.

You will learn

  • Spot the problem: one subclass for every combination of behaviours.
  • Wrap an object in another with the same interface that does its part and delegates.
  • Stack several decorators and know that their order changes the result.
  • Recognise decorators you already use: `BufferedReader` in Java and `@lru_cache` in Python.
  • Know when a decorator is overkill and what it costs.