Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Composite

Intent

Treat single items and groups of items through one shared contract, so client code handles a whole tree the same way it handles one leaf.

Motivation

A backup tool must total the size of a small file tree: a root folder holds file-a (100 KB) and a subfolder docs holding file-b (250 KB). Special-casing files versus folders at every step litters the code with type checks, and each new grouping rule edits them all. The composite gives files and folders one size step — a file returns its own size, a folder sums its children — so totaling the tree is one uniform call.

Structure

flowchart TD
  Client --> Node[Entry Contract]
  Node --> File[File Leaf]
  Node --> Folder[Folder Composite]
  Folder --> Node
  • Component (Entry) — the shared contract with a size step.
  • Leaf (File) — a single item; reports its own size.
  • Composite (Folder) — holds child entries and sums their sizes recursively.
  • Client — calls size once, unaware whether it holds a file or a folder.

Consequences

  • Benefit: tree operations stay uniform — new operations and deeper nesting need no client branching.
  • Cost / trade-off: the shared contract can leak odd steps onto leaves (a file has no children); keeping every node honest takes discipline.

Basic Recap

Composite represents individual objects and groups of objects behind one common component interface. Clients perform an operation on a whole structure without constantly testing whether they hold a leaf or a container. A composite typically forwards work to its children and combines their results. The model fits true whole-part hierarchies; shared children, cycles, and cross-links need additional rules rather than pretending every graph is a tree.

Complex Scenario

A CI runner models a pipeline as stages, sequential groups, and parallel groups. The scheduler can request execution, cancellation, or a status summary through the same PipelineComponent interface at any depth. Leaves run individual jobs, while composites coordinate their children and reduce job outcomes into a group outcome. This lets a nested optional test suite behave like any other stage from the scheduler’s perspective.

Edge cases

  • Ordering: Sequential groups must stop or continue after failure according to an explicit policy, while dependency links between branches must not be mistaken for ordinary parent-child containment.
  • Concurrency: Parallel groups need bounded fan-out and cancellation that reaches running descendants without corrupting the shared result reducer.
  • Partial failure: A group with cancelled, failed, and successful children must preserve each outcome instead of returning an ambiguous single failure.

Traversal needs a visited set if the configuration format permits reused nodes; otherwise a cycle turns one uniform call into unbounded recursion.

Sketch (illustrative pseudocode, not runnable):

ParallelGroup.run(context):
    children.ready(context).forEach(scheduleWithLimit)

    for completion in completions:
        outcomes.record(completion.childId, completion.result)
        if policy.shouldCancel(completion.result):
            context.cancelRemaining()
    return reduceOutcomes(outcomes, policy)

JobLeaf.run(context):
    return runner.execute(this.jobSpec, context.cancellation)

Pipeline.status():
    return root.summarizeUsing(visited = {})

When to Use / When Not to Use

Use when:

  • Data forms a part-whole tree (files, menus, org charts) and clients should treat one item and a group alike.
  • Operations like size, render, or export must recurse without client-side type checks.

Avoid when:

  • The structure is flat or leaves and groups need wholly different operations — the shared contract becomes misleading.
  • Ordering or distinct child roles matter more than uniform treatment.

Examples

Links to runnable code (same scenario, four languages):

  • examples/elixir/composite/
  • examples/dart/composite/
  • examples/go/composite/
  • examples/rust/composite/

Expected outcome: listing the tree contents and printing the total size of 350 KB.

Anti-pattern / Failure Mode

  • Misuse: Forcing leaf and container to share operations that make no sense for leaves.

  • Review signal: Leaves throwing ‘unsupported’ for half the interface.

  • Misuse symptom: Leaf classes inherit meaningless child-management methods, or every caller still downcasts components to discover what they can do. A composite is also misused when a many-to-many dependency graph is forced into a parent-child tree to obtain recursive convenience.

  • Review signal: Look for isGroup branches in client code, empty add/remove implementations on leaves, and recursive operations with no cycle or depth protection. Production traces that lose child failures behind one group error indicate that uniform treatment has erased necessary diagnostic detail.

  • Decorator — uniform trees vs combinable wrappers.
  • Iterator — walk the tree without exposing storage.
  • Visitor — add operations over the structure without editing it.

Exercise

Add a count step returning the number of files in a subtree (folders count 0 themselves). Root must report 2 without any client branching on file versus folder.

Self-check

  • Where does the recursion live?
    AnswerIn the folder composite — it calls size on each child, which recurses for subfolders.
  • What does the client skip?
    AnswerType checks — it calls one step on the contract and never asks file-or-folder.
  • When is Composite wrong?
    AnswerWhen leaves and groups share no meaningful operation; forcing one contract then confuses both.