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 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.
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.
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.)
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.
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.”
A group is just another item. One question, all the way down.
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.
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.”
add livesFour 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 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.
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.
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.)
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.
Its look-alikes:
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 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.
add.Checklist:
add and remove live?One question, all the way down.
Related lessons: Command, Decorator, Proxy, Polymorphism.
java.awt.Container and
javax.swing.JComponent javadoc.