# CompositeSplitting one task into a sub-phase silently drops sixteen hours from an estimate. Learn how the Composite pattern makes a group just another item, how the recursion works, and where Swing and file trees use it.

How long will the website launch take? Design is a task, eight hours. Build is a phase, with
frontend and backend inside it. Then testing. Your total code adds it all up: fifty hours. Then
someone splits backend into its own phase, with an API and a database. And the estimate quietly
drops sixteen hours. No error. No warning. Just a wrong number. Why does splitting a task lose its
hours? The fix is called the **Composite** pattern.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows
it section by section, with diagrams and a little extra depth.

{{< lesson-video youtube="vLAoOdELul0" title="Composite" >}}

## The estimate that lost sixteen hours

The plan is a little tree: Launch site holds Design (8 h), Build and Testing (6 h); Build holds
Frontend (20 h) and Backend (16 h). Once Backend becomes a phase of its own (API 10 h, Database
6 h), the old total code says 34 h instead of 50 h. Code that treats a group differently from a
single item breaks when groups nest.

```mermaid {alt="The launch plan as a tree: Launch site holds Design (8 h), Build and Testing (6 h); Build holds Frontend (20 h) and Backend; Backend, now a phase, holds API (10 h) and Database (6 h). The old total code skips Backend and reports 34 h instead of 50 h." caption="Backend became a phase, and its 16 hours vanished."}
flowchart TD
  L["Launch site"] --> D["Design 8 h"]
  L --> B["Build"]
  L --> T["Testing 6 h"]
  B --> F["Frontend 20 h"]
  B --> K["Backend (now a phase)"]
  K --> A["API 10 h"]
  K --> DB["Database 6 h"]
  class L,B c5
  class D,T,F,A,DB c1
  class K bad
```

## Recipe cards

Picture a recipe card for a cake. It lists eggs, flour, and sugar. And one more line: a batch of
frosting, see card twelve. What does the cake cost? The card adds up its lines. Eggs just know
their price. For the frosting, you ask card twelve. It adds up its own lines, and hands back one
number. Same question, at every level. You never had to ask whether a line was an ingredient or a
whole card.

| Cake card | Price | | Frosting (card 12) | Price |
|---|---|---|---|---|
| eggs | 2.00 | | butter | 2.50 |
| flour | 1.00 | | icing sugar | 1.00 |
| sugar | 0.50 | | **total** | **3.50** |
| frosting → card 12 | 3.50 | | | |
| **total** | **7.00** | | | |

In code, anything you can ask is a **component**. An ingredient is a **leaf**. A card is a
**composite**. And you, asking, are the **client**.

```mermaid {alt="The recipe analogy mapped onto code: any line you can ask is the component (WorkItem); an ingredient is a leaf (Task); a card is a composite (Phase); you, asking, are the client (the estimate screen)." caption="The same question at every level."}
flowchart LR
  A["any line on a card"] --> A2["component: WorkItem"]
  B["an ingredient"] --> B2["leaf: Task"]
  C["a recipe card"] --> C2["composite: Phase"]
  D["you, asking"] --> D2["client: Estimate screen"]
  class A2 c6
  class B2 c1
  class C2 c5
  class D2 c4
```

## The obvious version: ask every item what kind it is

Here's a task. A name, and some hours.

```java
public record Task(String name, int hours) {}
```

A phase holds a list of items. So to total the plan, you loop, and you check what each item is. A
task adds its hours. A phase, you loop over its items, and add theirs.

```java
int total = 0;
for (Object item : plan) {
    if (item instanceof Task t) {
        total += t.hours();
    } else if (item instanceof Phase p) {
        for (Object inner : p.items()) {
            if (inner instanceof Task t) {
                total += t.hours();
            }
        }
    }
}
```

For a plan that's always two levels deep, that's fair. It's short, and you can read it from top to
bottom. It's also the code most of us write first. Nothing about it is wrong, until the plan changes
shape. (Here `plan` is a `List<Object>` and the naive `Phase` has an `items()` list.)

## Why it breaks

But the loop is exactly as deep as the plan was, on the day you wrote it. Put a phase inside a
phase, and the inner check only knows tasks. Backend falls through, and its hours are skipped without
a sound. The fix is another nested loop. And another one for the level after that.

Worse, the same check gets pasted into every operation. The total, printing the plan, the progress
bar, the deadline. And a new kind of item, like a milestone, means editing all four. Every one of
those checks has to change together, and the compiler won't tell you which one you missed.

```mermaid {alt="A new item kind, Milestone, forces edits to four operations (total, print, progress, deadline), each of which repeats the same 'if task, else if phase' type check; the compiler can't point at the one you forget." caption="One new kind, four type checks to edit."}
flowchart LR
  M["new kind: Milestone"] --> O1["total: if task / else if phase"]
  M --> O2["print: if task / else if phase"]
  M --> O3["progress: if task / else if phase"]
  M --> O4["deadline: if task / else if phase"]
  class M warn
  class O1,O2,O3,O4 bad
```

## The key idea: the group is just another item

Here's the shift. Make a phase the same kind of thing as a task. Both are work items, and both can
answer `hours()`:

```java
public interface WorkItem {
    String name();
    int hours();
}
```

A task answers with its own number. A phase answers by asking each of its parts, and adding up. The
estimate screen asks one question of the top item. It never checks a type again.

The Gang of Four say Composite "lets clients treat individual objects and compositions of objects
uniformly." Their full intent: *"Compose objects into tree structures to represent part-whole
hierarchies."*

```mermaid {alt="Class diagram: the Estimate screen uses the WorkItem interface; Task and Phase both implement WorkItem; Phase holds a list of WorkItem parts, so a phase can contain tasks and other phases." caption="A group is just another item."}
classDiagram
  class Estimate
  class WorkItem {
    <<interface>>
    +name() String
    +hours() int
  }
  class Task {
    +hours() int
  }
  class Phase {
    -parts: List
    +add(part) Phase
    +hours() int
  }
  Estimate --> WorkItem : asks hours()
  WorkItem <|.. Task
  WorkItem <|.. Phase
  Phase o--> WorkItem : parts
```

> **A group is just another item. One question, all the way down.**

## Building it: the recursion

The task becomes a record that implements work item. Its accessors already are `name()` and
`hours()`, so there's nothing else to write.

```java
public record Task(String name, int hours) implements WorkItem {}
```

The phase holds a list of work items, any mix of tasks and phases. `add` returns the phase, so a
plan reads like an outline. And `hours` loops over its parts and asks each one. A part that's a
phase does the same thing, one level down.

```java
public class Phase implements WorkItem {
    private final String name;
    private final List<WorkItem> parts = new ArrayList<>();

    public Phase(String name) { this.name = name; }

    public Phase add(WorkItem part) {
        parts.add(part);
        return this;
    }

    public String name() { return name; }

    public int hours() {
        int total = 0;
        for (WorkItem part : parts) {
            total += part.hours();
        }
        return total;
    }
}
```

Now build the launch plan, three levels deep, and ask it once:

```java
WorkItem launch = new Phase("Launch site")
        .add(new Task("Design", 8))
        .add(new Phase("Build")
                .add(new Task("Frontend", 20))
                .add(new Phase("Backend")
                        .add(new Task("API", 10))
                        .add(new Task("Database", 6))))
        .add(new Task("Testing", 6));
```

Launch asks design, then build. Build asks frontend, then backend. Backend asks its two tasks, and
answers sixteen. Build answers thirty six, testing adds six, and the launch answers fifty. Every
hour is counted.

```mermaid {alt="Sequence of hours() calls: Launch asks Design (8) and Build; Build asks Frontend (20) and Backend; Backend asks API (10) and Database (6) and answers 16; Build answers 36; Launch asks Testing (6) and answers 50." caption="launch.hours() = 50"}
sequenceDiagram
  participant L as Launch
  participant B as Build
  participant K as Backend
  participant T as Tasks
  L->>T: Design.hours()
  T-->>L: 8
  L->>B: hours()
  B->>T: Frontend.hours()
  T-->>B: 20
  B->>K: hours()
  K->>T: API, Database
  T-->>K: 10 + 6
  K-->>B: 16
  B-->>L: 36
  L->>T: Testing.hours()
  T-->>L: 6
  Note over L: 8 + 36 + 6 = 50
```

Each node only knows its own parts. A new level costs no code at all, and a new kind of item is
just one more class (a `Milestone` with zero hours slots straight into the tree). The Gang of Four
list this as a consequence: "Newly defined Composite or Leaf subclasses work automatically with
existing structures and client code."

## Anatomy, and where `add` lives

Four roles. Work item is the **component**. Task is the **leaf**. Phase is the **composite**. And
the estimate screen is the **client**.

Now the real design choice. Who declares `add`? We put it only in phase. That's the **safe**
version. Adding to a task can't even compile. The cost is that code holding a work item has to know
it's a phase before it can add.

The other choice puts `add` in work item, with a default that throws. That's **transparency**.
Every item looks the same, but adding to a task fails only when it runs:

```java
public interface WorkItem {
    String name();
    int hours();

    default WorkItem add(WorkItem part) {
        throw new UnsupportedOperationException(name() + " has no parts");
    }
}
```

(`Phase.add` returning `Phase` is a legal covariant override of this default, and the `Task` record
simply inherits the throwing version.)

| | Safety: `add` only in `Phase` | Transparency: `add` in `WorkItem` |
|---|---|---|
| `task.add(…)` | compile error | exception at run time |
| Code holding a `WorkItem` | must know it's a `Phase` to add | can call `add` on anything |
| Interface | leaf and composite differ | one interface for all |

The Gang of Four chose transparency for the book ("We have emphasized transparency over safety in
this pattern"), and suggest that a leaf's `add` fail by default, "perhaps by raising an exception".
In Java, the safe version is the usual default. Just pick on purpose.

> **Transparency or safety: pick where add lives.**

## You already use it: Swing and file trees

Swing is built on this. A `Container` is a `Component` that holds other components. In the javadoc's
words, a container "is a component that can contain other AWT components". A panel holds a label and
a text field. It also holds another panel, with two buttons in it. And `add` takes either one.

```java
JPanel form = new JPanel();
form.add(new JLabel("Email"));
form.add(new JTextField(20));

JPanel buttons = new JPanel();
buttons.add(new JButton("Cancel"));
buttons.add(new JButton("Save"));
form.add(buttons);

frame.add(form);
```

When the window paints, each container passes the paint on to its children (`Container.paint`
"forwards the paint to any lightweight components that are children of this container"). It
doesn't care which are buttons, and which are panels.

```mermaid {alt="The form as a tree: the frame holds the form panel; the form holds a JLabel 'Email', a JTextField and a buttons panel; the buttons panel holds the Cancel and Save buttons. Paint flows from the frame down to every child." caption="Panels inside panels; paint flows down the tree."}
flowchart TD
  FR["frame"] --> FO["form: JPanel"]
  FO --> LB["JLabel Email"]
  FO --> TF["JTextField"]
  FO --> BP["buttons: JPanel"]
  BP --> C1["JButton Cancel"]
  BP --> C2["JButton Save"]
  class FR,FO,BP c5
  class LB,TF,C1,C2 c1
```

Swing even picked transparency. Every Swing component is a container, so a button has an `add`
method too: `JButton` → `AbstractButton` → `JComponent` → `Container` → `Component`.

File trees have the same shape. A folder is a file that holds files, and its size is the sizes of
everything inside: `docs` holds `notes.txt` (2 KB) and `photos`, which holds `beach.jpg` (3 KB) and
`cat.jpg` (4 KB), so `photos` is 7 KB and `docs` is 9 KB. (In `java.io.File`, a directory is a `File`
too, and `listFiles()` returns what's inside it.)

## The mix-up: holding a list isn't enough

Now a common mix up: any object that holds a list is a composite. Not quite. A team with a list of
tasks is just a class with a list. The pattern is when the group is the same type as its parts, so
callers can't tell them apart.

```mermaid {alt="Side by side: Team has a List of Task but is not a WorkItem, so it isn't a composite; Phase implements WorkItem and holds WorkItems, so it can stand wherever a single item is expected." caption="It's a composite when the group passes for one of its parts."}
flowchart LR
  subgraph NO["Not a composite"]
    direction TB
    TM["Team"] --> TL["List of Task"]
  end
  subgraph YES["Composite"]
    direction TB
    PH["Phase<br/>is a WorkItem"] --> PW["holds WorkItems"]
  end
  NO ~~~ YES
  class TM muted
  class PH c5
  class PW c6
```

Its look-alikes:

- A **decorator** also wraps something of its own type, but only one, and it adds a job. The Gang of
  Four call it "a degenerate composite with only one component" (see
  [Decorator](/patterns/decorator-pattern/)).
- A **macro command** is a composite of commands (see [Command](/patterns/command-pattern/)).
- An **[iterator](/patterns/iterator-pattern/)** walks a composite. The composite is the tree it walks.

Here's a quick test. Could you hand the group to code that expects a single item? If you can, it's a
composite.

## When not to use it

When should you skip it? If the shape is fixed and shallow, a plain list is clearer. An order has
lines, and lines never have lines. If leaves and groups share almost nothing, a forced common
interface turns into methods that half the classes can't keep.

The Gang of Four warn it can make a design overly general: "it makes it harder to restrict the
components of a composite … You'll have to use run-time checks instead." The types can't stop a task
going where it shouldn't, so you check at run time.

And keep it a tree. Put build inside build, and `hours` calls itself until the stack overflows
(`StackOverflowError`). Like a recipe card that says, see this card. Use it when groups nest, and
callers shouldn't care which one they're holding.

```mermaid {alt="Decision: can groups contain groups? If not, use a plain list. Do leaves and groups share the operations callers need? If not, don't force a common interface. Otherwise use Composite, and keep it a tree with no cycles." caption="Use it when groups nest and callers shouldn't care."}
flowchart TD
  Q1{"Can groups contain groups?"} -->|no| A1["a plain list is enough"]
  Q1 -->|yes| Q2{"Do leaves and groups share<br/>the operations callers need?"}
  Q2 -->|no| A2["don't force one interface"]
  Q2 -->|yes| A3["Composite: one interface"]
  A3 --> A4["keep it a tree: no cycles"]
  class A3 good
  class A4 warn
  class A1,A2 muted
```

## Recap

- When code asks "single item or group?" before every operation, it breaks as soon as groups nest.
- Give the leaf and the group one interface. The group answers by asking its parts.
- Choose safety or transparency for `add`.
- Swing and file trees work this way.
- A list field alone isn't a composite. And keep it a tree.

```mermaid {alt="Recap chain: one interface for leaf and group; the group asks its parts; the client asks the top item once; any depth works." caption="One question, all the way down."}
flowchart LR
  A["one interface"] --> B["group asks its parts"] --> C["client asks once"] --> D["any depth"]
  class A c6
  class B c5
  class D good
```

Checklist:

- Do your structures nest (groups inside groups), with no fixed depth?
- Do callers keep asking "is this a single item or a group?"
- Does the group implement the same interface as its parts?
- Did you choose, on purpose, where `add` and `remove` live?
- Can anything create a cycle? If so, guard against it.

> **One question, all the way down.**

Related lessons: [Command](/patterns/command-pattern/), [Decorator](/patterns/decorator-pattern/),
[Proxy](/patterns/proxy-pattern/), [Polymorphism](/fundamentals/polymorphism/).

## Further reading

- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, *Design Patterns* (1994): Composite.
- [`java.awt.Container`](https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/java/awt/Container.html) and
  [`javax.swing.JComponent`](https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/swing/JComponent.html) javadoc.
