Pattern 10/22 · Structural

Composite

Give leaves and branches one shared interface in which every operation is defined recursively: a leaf answers directly, a branch answers by asking its children. Calling code can then handle a single element and an entire tree with exactly the same code.

Structural●●○13 min read8 stepsalso known as: Object Tree, Node Tree
structuralrecursiontreeleafLSPUI

01 — It starts with code that is breaking

Problem

You're building a shopping cart. At first there's only Product { name, price } and Cart { items }, and the total is a loop. Then marketing starts selling bundles: "Travel package = flight + hotel + insurance", priced as the sum of its parts, and bundles can contain bundles. You add Bundle { items }.

The total loop breaks immediately: sum += item.price no longer works for Bundle, because a bundle has no price. You write if (item instanceof Bundle) sum += totalOf(item.items) else sum += item.price. Done — until totalOf() also hits nested bundles and you add recursion there too. Then renderLine(), then discountFor(), then validateStock(). Every function has to remember that this tree is nested, and the one that forgets produces a wrong number.

Wherever there's a tree, there's the same pain. Menus and submenus in a food app; comments with replies, and replies to replies; file systems; breadcrumbs; the AST ESLint walks; Vue's component tree. The pattern repeats: a traverse(node) function with if (node.children) poking out at the top, and a few instanceof branches behind it. Every if (node.children) is a Composite that was never born.

The consequences as the project grows are mechanical: adding a new node type (say GiftCard — a leaf, priced 0, but not counted in the total) forces you to open every call site that has an instanceof, and the compiler can't point at the ones you missed because the final else is usually a silent sum += 0. Bugs like this don't crash — they put the wrong number on an invoice.

The deeper cause is in the types: Product and Bundle can both answer "how much does it cost", "how is it rendered", "is it in stock", but the type system doesn't know that, so every call site has to rebuild the recursion itself and remember which cases are still missing.

02 — The idea, before touching code

Solution

Composite: bring leaves and branches under one interface, and define each operation recursively right in that interface. A leaf's size() is a number; a branch's size() is the sum of its children's size(). Nothing outside those two classes knows the difference between a leaf and a branch.

The client therefore only holds an FsNode, and one function works for both: printing a file or printing an entire folder is the same call. The recursion lives in exactly one place, is tested in one place, and when you add a new node type, not a single call site has to change.

The cost, stated up front: if the interface has add(child), leaves have to fake it (throw an error or silently do nothing) — that's a sign of a Liskov violation. There are two ways to live with it, and you have to choose deliberately: a "transparent" interface (every node has add, leaves fake it) or a "safe" interface (split out CompositeNode extends FsNode with add, and a client that wants to add children has to know it's holding a composite). There is no free third option.

03 — Doing it for real, one code fragment per step

Step by step

1

List the node types and the operations that run on both leaves and branches

Composite is only worth it when there are shared operations across both kinds. Put the nodes on one axis (File, Folder, MenuItem, MenuCategory) and the operations on the other (total size, render, count, validate, serialize).

For each cell, ask: can this operation be defined for both leaves and branches? delete() makes no sense on a File — don't put it in the shared interface. The interface only takes what both sides can answer.

textoperation-matrix.txt
                size()  render()  count()  add()  delete()
File (leaf)       yes      yes       yes     no       yes
Folder (composite) yes      yes       yes     yes      yes
MenuItem (leaf)   yes      yes       yes     no       yes

=> shared interface: size, render, count
=> add/delete: composite side only (or accept that leaves fake it)
The "add" column is where you decide transparent vs safe. Don't decide it on gut feeling.
Key pointComposite lives on the intersection of leaves and branches. Get that intersection right, and the rest is just translating it into TypeScript.
2

Define the interface using exactly the recursive operations

The interface doesn't describe "the shape of a file", it describes how to ask a node. Notice render(depth): the depth parameter only exists because there's a tree — every node, leaves included, has to know which level it's on to draw itself.

This is where you choose: does add() go in the shared interface (transparent) or in a composite-only interface (safe)? The snippet below picks transparent so you can see its cost firsthand in Step 6.

tscomponent.ts
export interface FsNode {
  readonly name: string
  /** Leaf: returns bytes. Branch: sum of its children. */
  size(): number
  /** Returns multiple lines so the caller doesn't need to know the depth. */
  render(depth: number): string[]
  add(child: FsNode): void
}
Key pointThe right Composite interface is the set of questions that both leaves and branches can answer — not one method more.
3

Leaf: answer directly, no children

The leaf is where the recursion stops. A file's size() is data, not a loop; its render() returns exactly one line. If your leaf holds an empty children array just so it can call .reduce() like everyone else, you're letting composite logic leak down into the leaf.

tsleaf.ts
import type { FsNode } from './component'

export class FileEntry implements FsNode {
  constructor(readonly name: string, private bytes: number) {}

  size(): number { return this.bytes }

  render(depth: number): string[] {
    return ['  '.repeat(depth) + this.name + ' (' + this.bytes + ')']
  }

  // the price of a transparent interface:
  add(_child: FsNode): void { throw new Error('A file can\'t contain anything: ' + this.name) }
}
Four methods, no loops. The leaf doesn't need to know composites exist.
Key pointRecursion is only cheap when its base case is cheap. A leaf must be an O(1) computation, not a mini-tree.
4

Composite: collaborate by asking the children, one level only

A branch does not walk the whole tree. Its size() is a reduce over its direct children, each child taking care of its own part; if a child is a folder, that folder reduces in turn. Not a single line in FolderEntry mentions depth or "children of children".

That is the whole power of Composite: you write one step of the sum, and it's correct for a 2-level tree and a 2000-level tree alike, because the other nodes are responsible for the rest.

tscomposite.ts
import type { FsNode } from './component'

export class FolderEntry implements FsNode {
  private children: FsNode[] = []
  constructor(readonly name: string) {}

  add(child: FsNode): void { this.children.push(child) }

  size(): number {
    return this.children.reduce((sum, c) => sum + c.size(), 0)
  }

  render(depth: number): string[] {
    const lines = ['  '.repeat(depth) + this.name + '/ (' + this.size() + ')']
    for (const c of this.children) lines.push(...c.render(depth + 1))
    return lines
  }
}
Key pointEach node adds up exactly one step. Recursion handles the rest for you — as long as its base case is a real leaf.
5

Call sites only see the interface: one function for a leaf and a whole tree

Now look at it from the client side. No instanceof, no switch (node.kind), no idea what FolderEntry is. printSize(readme) and printSize(app) are the same line of code with two different arguments — which is why this pattern has a name in the book.

tsclient.ts
import type { FsNode } from './component'
import { FileEntry } from './leaf'
import { FolderEntry } from './composite'

const printSize = (node: FsNode): void => console.log(node.name + ': ' + node.size() + ' bytes')

const readme: FsNode = new FileEntry('README.md', 120)
const app = new FolderEntry('app')
app.add(new FileEntry('main.ts', 80))
app.add(readme)

printSize(readme) // a single leaf, on its own
printSize(app)    // the whole tree, same function, not a single branch
console
README.md: 120 bytes
app: 200 bytes
Key pointHow you know Composite worked: the number of call sites that distinguish leaves from branches drops to 0 (except where you genuinely add children).
6

Paying the price: the leaf fakes add(), and the transparent/safe choice

readme.add(x) is code that is type-correct but semantically wrong. You handle it with a throw — meaning the compiler can no longer stop you, and you only find out at runtime. This is exactly a Liskov violation: a subtype that can't behaviourally substitute for its supertype.

The "safe" option splits the interface: FsNode only has size/render, and CompositeNode extends FsNode adds add(). In exchange, a client that wants to add children has to know it's holding a composite — and the instanceofs you just chased out come back, at least wherever data is written. TypeScript also offers a comfortable halfway house: stay transparent but declare add?(child: FsNode) and call node.add?.(child) — leaves don't have to fake anything, but every caller has to handle the "not there" branch.

tssafe-version.ts
export interface FsNode { readonly name: string, size(): number }

export interface CompositeNode extends FsNode {
  add(child: FsNode): void          // only composites promise this
  isComposite(): true
}

// a caller that wants to add a child has to ask permission:
function addTo(node: FsNode, child: FsNode) {
  if (isComposite(node)) node.add(child)
  else throw new Error(node.name + ' can\'t contain anything')
}

const isComposite = (n: FsNode): n is CompositeNode => 'isComposite' in n
Safe = you lose transparency, but there are no fake methods. Transparent = the opposite. Pick based on the share of call sites that only read.
Key pointComposite trades transparency for safety. Don't pretend you don't have to choose — choose, and write a comment on the interface.
7

Add the real dimensions of a tree: depth, cycles, caching

The tree in this demo is 3 levels deep, so recursion is free. A real app's comment tree has unpredictable depth (200 levels of reply-to-reply is enough to hit the call stack ceiling), and if a user "replies" to a comment that is an ancestor of itself, you have a cycle — the recursion never comes back.

Two cheap defences: cap the depth (with an error message that states the depth), and block cycles right in add() by walking up the parent chain or using a visited Set. If aggregates (size, count) get called repeatedly on a large tree, cache them at the node and invalidate the cache in add/remove — don't recompute a thousand nodes for a single render.

tsguards.ts
const MAX_DEPTH = 64

class FolderEntry {
  private children: FsNode[] = []
  private cachedSize = -1

  add(child: FsNode): void {
    if ((child as unknown as { hasAncestor?: (n: object) => boolean }).hasAncestor?.(this)) {
      throw new Error('cannot put a node inside its own descendant')
    }
    this.children.push(child)
    this.cachedSize = -1 // invalidate the cache when the tree changes
  }

  size(depth = 0): number {
    if (depth > MAX_DEPTH) throw new Error('tree is abnormally deep, possible cycle')
    if (this.cachedSize < 0) {
      this.cachedSize = this.children.reduce((s, c) => s + c.size(depth + 1), 0)
    }
    return this.cachedSize
  }
}
These three guard lines are worth more than any unit test: they turn a stack overflow into an error with a name.
Key pointRecursion + user-supplied data = you need a depth cap and cycle detection. No exceptions.
8

Measure whether it's worth it: files touched when adding a new node

The final test, and the only trustworthy one: add a new leaf type (Symlink) and count the files you have to change. It should be 1. If you have to touch client.ts, renderer.ts, validator.ts, there's still a stray instanceof somewhere — find it and kill it.

If what you add most often is new operations (search, diff, export) rather than new nodes, a recursive Composite forces you to edit every class once per operation. That's when Visitor shows up — see visitor. And if your tree has a fixed 2 levels and 4 node types, chances are you don't need this pattern: a flat array and a parentId field are much cheaper.

tssymlink.ts
// The one and only NEW file. FolderEntry untouched, client untouched.
export class Symlink implements FsNode {
  constructor(readonly name: string, private target: FsNode) {}
  size(): number { return this.target.size() }
  render(depth: number): string[] { return ['  '.repeat(depth) + this.name + ' -> ' + this.target.name] }
  add(child: FsNode): void { this.target.add(child) }
}
Key pointComposite wins when adding nodes and loses when adding operations. Know which axis changes more often before you pick it.

04 — Who talks to whom

Structure

  • ComponentThe shared interface: `size()`, `render(depth)`. Every question both leaves and branches can answer.
  • LeafAn element with no children. Each method is a direct computation; this is the base case of the recursion.
  • CompositeAn element with `children: Component[]`. Each method = ask each child, then combine the results.
  • ClientOnly holds a `Component`. Calls a single element and a whole tree with exactly the same line of code.
  • Client-Writer (optional)The place that genuinely adds/removes children — where you tell Composite from Leaf (the "safe" version) or catch the `throw` (the "transparent" version).
              ┌───────────────────────────────┐
              │ Component (interface)         │
              │  + name: string               │
              │  + size(): number             │
              │  + render(depth): string[]    │
              │  + add(child)   ← leaf fakes! │
              └──────────────┬────────────────┘
                    ┌────────┴────────┐
                    ▼                 ▼
        ┌───────────────────┐   ┌───────────────────────┐
        │ Leaf (FileEntry)  │   │ Composite (Folder)    │
        │  size() = bytes   │   │  children: FsNode[]   │
        │  add() -> throw   │   │  size() = Σ c.size()  │
        └───────────────────┘   └───────────┬───────────┘
                                            │ recursion: direct children only
                        ┌───────────────────┼───────────────────┐
                        ▼                   ▼                   ▼
                   FolderEntry          FileEntry           FolderEntry
                   (sub-branch)           (leaf)              (branch)

   Client only holds FsNode → doesn't know (or care) which one it has.

05 — Edit freely, run it right here

Try it: the same `size()`/`render()` for a file and for a whole tree

tsdemo.ts
interface FsNode {
  readonly name: string
  size(): number
  render(depth: number): string[]
  add(child: FsNode): void
}

class FileEntry implements FsNode {
  constructor(readonly name: string, private bytes: number) {}
  size(): number { return this.bytes }
  add(_child: FsNode): void { throw new Error('A file can\'t contain anything: ' + this.name) }
  render(depth: number): string[] { return ['  '.repeat(depth) + this.name + ' (' + this.bytes + ')'] }
}

class FolderEntry implements FsNode {
  private children: FsNode[] = []
  constructor(readonly name: string) {}
  add(child: FsNode): void { this.children.push(child) }
  size(): number { return this.children.reduce((sum, c) => sum + c.size(), 0) }
  render(depth: number): string[] {
    const lines = ['  '.repeat(depth) + this.name + '/ (' + this.size() + ')']
    for (const c of this.children) lines.push(...c.render(depth + 1))
    return lines
  }
}

const src = new FolderEntry('src')
src.add(new FileEntry('App.vue', 240))
const utils = new FolderEntry('utils')
utils.add(new FileEntry('format.ts', 150))
utils.add(new FileEntry('parse.ts', 250))
src.add(utils)

const root = new FolderEntry('app')
root.add(src)
const readme = new FileEntry('README.md', 120)
root.add(readme)

console.log(root.render(0).join('\n'))
console.log('total: ' + root.size())
try { readme.add(new FileEntry('x.ts', 10)) }
catch (e) { console.log('the leaf has to fake add() too: ' + (e as Error).message) }
console
app/ (760)
  src/ (640)
    App.vue (240)
    utils/ (400)
      format.ts (150)
      parse.ts (250)
  README.md (120)
total: 760
the leaf has to fake add() too: A file can't contain anything: README.md

The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.

06 — Honest about the cost

When to use it, when not to

Use it when

  • The domain really is a tree: menus/categories, file systems, comments with replies, org charts, breadcrumbs, ASTs, the DOM, component trees.
  • The client wants to treat a single element and a whole group as one: same total, same render, same send (the "composite unit" idea).
  • You can count ≥ 2 node types and ≥ 2 shared operations that work on both leaves and branches.
  • New node types show up more often than new operations (the reverse case suits Visitor better).
  • You want one single place that holds the recursion, so depth limits, caching and errors are controlled there.
  • Don't use it if the structure is flat and fixed (order → items, post → tags): an artificial parent/child relationship just adds a layer of indirection.

Don't use it when

  • The LSP tax. add() on the shared interface forces leaves to fake it — throw, a no-op, or returning false are all the signature of a compromised design. Choose transparent/safe deliberately, don't let it happen by accident.
  • JS-style over-generalisation. Halfway through, someone always writes interface Node { type: string, children: Node[], meta: Record<string, any> }. The tree is truly generic, but in return node.meta.price is any and nobody knows what a node is anymore. Composite pays off when the interface is strong (size(): number), not when everything is melted into one generic shape.
  • Recursion isn't free: there's a call stack ceiling (a few thousand levels and you crash), and user-created cycles (replying to your own ancestor) turn rendering into an infinite loop. A depth cap + cycle detection are mandatory, not optional.
  • Measure: Σ size() on every render is O(N) per frame. For large trees, cache at the composite and invalidate in add/remove; otherwise the UI gets slow and the profiler points at exactly one recursive function.
  • Composite + many operations = every new operation means editing every class. If that is your main axis of change, don't force it: switch to Visitor, or move the behaviour into pure functions that take a Component.

07 — You have met it already, just not by name

In real code

The DOM: Node is the composite, Text is a leaf

Element (composite) and Text/Comment (leaves) all implement Node, and element.textContent is a recursive sum over the whole subtree — you don't need to know how many levels are in between. Conversely, calling appendChild on a Text node fails: exactly the "leaf has to fake add()" tax that even browsers can't avoid.

Vue's VNode tree

Templates compile into a VNode tree: Fragment (multiple root nodes, v-for) is a composite, text/comment vnodes are leaves, and patch() in runtime-core is one recursive function that handles every kind without knowing how deeply components are nested. Nested <RouterView>/<NuxtPage> with nested layouts is this very tree.

@babel/traverse, ESLint, PostCSS

Each AST node has a type and child fields; visitorKeys tells the traverser which fields are children, so your plugin writes enter(node) exactly once and it runs correctly on every node type. The nested structure is a Composite, and the traverser is a client that knows nothing about concrete node types.

JSON: composite in its purest form

JSON.stringify needs only one recursive algorithm: objects/arrays are composites, string/number/boolean/null are leaves. There's not a single if (typeof value === "object" && depth === 2), because leaves and composites answer the same question: "what do I serialize to".

08 — Try it yourself

Exercise

A food app's menu has `MenuItem { name, price }` and `MenuCategory { name, items }`, and the call site currently says `if (item instanceof MenuCategory)`. Convert it to Composite with `total()` and `render(depth)`, then add `Combo` (a group with 10% off its total) **without touching the call site**.

Hints, open them one at a time:

  1. What does the shared interface need? Hint: name, total(): number, render(depth): string[] — and where does add() go?
  2. A composite must not add up its grandchildren's prices: it only asks its direct children. Σ child.total() is enough.
  3. Combo differs from MenuCategory in exactly one place — extend the composite instead of rewriting the loop.

Declare interface MenuNode { name, total(), render(depth) }. MenuItem implements it directly (leaf). MenuCategory holds nodes: MenuNode[], total() is a reduce, render() adds indentation and recurses into children. Combo extends MenuCategory only overrides total() with super.total() * 0.9. The call site stays console.log(menu.total()).

tsexercise.ts
interface MenuNode {
  readonly name: string
  total(): number
  render(depth: number): string[]
}

class MenuItem implements MenuNode {
  constructor(readonly name: string, private price: number) {}
  total() { return this.price }
  render(d: number) { return ['  '.repeat(d) + this.name + ': ' + this.total()] }
}

class MenuCategory implements MenuNode {
  protected nodes: MenuNode[] = []
  constructor(readonly name: string) {}
  add(n: MenuNode) { this.nodes.push(n) }
  total() { return this.nodes.reduce((s, n) => s + n.total(), 0) }
  render(d: number): string[] {
    const out = ['  '.repeat(d) + this.name + ' = ' + this.total()]
    for (const n of this.nodes) out.push(...n.render(d + 1))
    return out
  }
}

class Combo extends MenuCategory { // NEW node, call site untouched
  total() { return Math.round(super.total() * 0.9) }
}

const tour = new Combo('Travel package')
tour.add(new MenuItem('Flight ticket', 1_500_000))
const hotel = new MenuCategory('Hotel')
hotel.add(new MenuItem('2 nights', 900_000))
hotel.add(new MenuItem('Breakfast', 200_000))
tour.add(hotel)

console.log(tour.render(0).join('\n'))
console.log('single item: ' + new MenuItem('Coffee', 45_000).total())

09 — Read them in pairs to see the essence

Related patterns

  • IteratorWhen the client needs to **walk** the tree instead of calling an aggregate operation, Iterator is how you move the recursion out of the client. Composite + Iterator are a classic pair (preorder/postorder tree traversal).
  • VisitorBoth deal with trees, along opposite axes: Composite puts behaviour into the nodes (new nodes are cheap, new operations are expensive); Visitor pushes behaviour out (new operations are cheap, new nodes are expensive).
  • DecoratorBoth "share the interface of the thing they contain", but a Decorator wraps **exactly one** object to add responsibility, while a Composite holds **many** objects to combine results. A stack of decorators is also a tree — just a single-branch one.
  • FlyweightWhen leaves repeat thousands of times (glyphs in text, chess pieces, icons), Flyweight lets the leaves share one object while Composite keeps the tree of references to them.