Composite

November 26, 20269 minutes

Splitting 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.

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.

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. 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.
Backend became a phase, and its 16 hours vanished.

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 cardPriceFrosting (card 12)Price
eggs2.00butter2.50
flour1.00icing sugar1.00
sugar0.50total3.50
frosting → card 123.50
total7.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.

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). 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).
The same question at every level.

The obvious version: ask every item what kind it is

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

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.

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.

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. 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.
One new kind, four type checks to edit.

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():

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.”

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. 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.
A group is just another item.

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.

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.

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:

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.

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. 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.
launch.hours() = 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:

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 PhaseTransparency: add in WorkItem
task.add(…)compile errorexception at run time
Code holding a WorkItemmust know it’s a Phase to addcan call add on anything
Interfaceleaf and composite differone 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.

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.

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. 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.
Panels inside panels; paint flows down the tree.

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.

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. 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.
It's a composite when the group passes for one of its parts.

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).
  • A macro command is a composite of commands (see Command).
  • An iterator 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.

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. 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.
Use it when groups nest and callers shouldn't care.

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.
Recap chain: one interface for leaf and group; the group asks its parts; the client asks the top item once; any depth works. Recap chain: one interface for leaf and group; the group asks its parts; the client asks the top item once; any depth works.
One question, all the way down.

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, Decorator, Proxy, Polymorphism.

Further reading