Composite: Boxes Inside Boxes
When the tracker weighs a shipment by asking every item "are you a box or a pallet?", it needs one more nested loop for every level of pallets, and a pallet on a pallet on a pallet gets missed; with the Composite pattern, a box and a pallet answer the same question, and a pallet answers by asking what's on it.
Journeyman · OOP · Updated
After this lesson you can
- Let a single item and a group of items answer the same question, so code treats them alike
- Spot the smells that point to Composite: "is it a box or a pallet?" checks and one nested loop per level
- Tell Composite from Decorator by what each one is for
Key takeaways
- The smell: "is it a box or a pallet?" checks, the same nesting copied into every method, and one more loop for every level.
- The cause: the code treats a single thing and a group of things as two different kinds, so it has to know how deep they go.
- The fix: a box and a pallet keep the same promise, weight(); a pallet answers by asking each thing on it, however deep.
- Composite holds many things and combines their answers; Decorator wraps one thing and adds to its answer.
Before this: Meet the Package Tracker, interfaces (a promise any class can keep), and object diagrams (a snapshot of real objects).
Lakeside Parcel's boxes weigh 2, 5 or 8 pounds, and big customers ship them on a pallet, the wooden platform a forklift lifts. Last month a customer started putting small pallets on top of big ones. Carriers price by weight, so the tracker has to weigh a shipment, and it has to count the boxes for the label. This lesson ends with a pattern called Composite; first, the weighing code, and the pallet it can't see.
The symptom: one more loop for every level
This week's shipment is a loose 5-pound box and one pallet. The pallet holds an 8-pound box, a 2-pound box and a small pallet; the small pallet holds a 2-pound box and a 5-pound box. That's five boxes, 22 pounds. Here's what the tracker says:
List<IShippingItem> shipment = new List<IShippingItem>
{
new Box(5),
new Pallet(new List<IShippingItem> { new Box(8), new Box(2), new Pallet(new List<IShippingItem> { new Box(2), new Box(5) }) }),
};
Console.WriteLine( quot;Total weight: {TotalWeight(shipment)} lb");
Console.WriteLine( quot;Boxes: {CountBoxes(shipment)}");
int TotalWeight(List<IShippingItem> items)
{
int total = 0;
foreach (IShippingItem item in items)
{
if (item is Box box) { total += box.Pounds; }
else if (item is Pallet pallet)
{
foreach (IShippingItem inner in pallet.Items)
{
if (inner is Box innerBox) { total += innerBox.Pounds; }
// A pallet on a pallet? Pallets didn't stack when this was written.
}
}
}
return total;
}
int CountBoxes(List<IShippingItem> items)
{
int count = 0;
foreach (IShippingItem item in items)
{
if (item is Box) { count++; }
else if (item is Pallet pallet)
{
foreach (IShippingItem inner in pallet.Items)
{
if (inner is Box) { count++; }
}
}
}
return count;
}
// Anything that can go in a shipment.
interface IShippingItem { }
class Box : IShippingItem
{
public int Pounds { get; }
public Box(int pounds) { Pounds = pounds; }
}
class Pallet : IShippingItem
{
public List<IShippingItem> Items { get; }
public Pallet(List<IShippingItem> items) { Items = items; }
}
Total weight: 15 lb
Boxes: 3
// Anything that can go in a shipment.
interface ShippingItem { }
record Box(int pounds) implements ShippingItem { }
record Pallet(List<ShippingItem> items) implements ShippingItem { }
int totalWeight(List<ShippingItem> items) {
int total = 0;
for (ShippingItem item : items) {
if (item instanceof Box box) { total += box.pounds(); }
else if (item instanceof Pallet pallet) {
for (ShippingItem inner : pallet.items()) {
if (inner instanceof Box innerBox) { total += innerBox.pounds(); }
// A pallet on a pallet? Pallets didn't stack when this was written.
}
}
}
return total;
}
int countBoxes(List<ShippingItem> items) {
int count = 0;
for (ShippingItem item : items) {
if (item instanceof Box) { count++; }
else if (item instanceof Pallet pallet) {
for (ShippingItem inner : pallet.items()) {
if (inner instanceof Box) { count++; }
}
}
}
return count;
}
void main() {
List<ShippingItem> shipment = List.of(
new Box(5),
new Pallet(List.of(new Box(8), new Box(2), new Pallet(List.of(new Box(2), new Box(5))))));
IO.println("Total weight: " + totalWeight(shipment) + " lb");
IO.println("Boxes: " + countBoxes(shipment));
}
Total weight: 15 lb
Boxes: 3
class Box:
def __init__(self, pounds):
self.pounds = pounds
class Pallet:
def __init__(self, items):
self.items = items
def total_weight(items):
total = 0
for item in items:
if isinstance(item, Box):
total += item.pounds
elif isinstance(item, Pallet):
for inner in item.items:
if isinstance(inner, Box):
total += inner.pounds
# A pallet on a pallet? Pallets didn't stack when this was written.
return total
def count_boxes(items):
count = 0
for item in items:
if isinstance(item, Box):
count += 1
elif isinstance(item, Pallet):
for inner in item.items:
if isinstance(inner, Box):
count += 1
return count
shipment = [Box(5), Pallet([Box(8), Box(2), Pallet([Box(2), Box(5)])])]
print(f"Total weight: {total_weight(shipment)} lb")
print(f"Boxes: {count_boxes(shipment)}")
Total weight: 15 lb
Boxes: 3
class Box {
constructor(pounds) { this.pounds = pounds; }
}
class Pallet {
constructor(items) { this.items = items; }
}
function totalWeight(items) {
let total = 0;
for (const item of items) {
if (item instanceof Box) { total += item.pounds; }
else if (item instanceof Pallet) {
for (const inner of item.items) {
if (inner instanceof Box) { total += inner.pounds; }
// A pallet on a pallet? Pallets didn't stack when this was written.
}
}
}
return total;
}
function countBoxes(items) {
let count = 0;
for (const item of items) {
if (item instanceof Box) { count++; }
else if (item instanceof Pallet) {
for (const inner of item.items) {
if (inner instanceof Box) { count++; }
}
}
}
return count;
}
const shipment = [new Box(5), new Pallet([new Box(8), new Box(2), new Pallet([new Box(2), new Box(5)])])];
console.log(`Total weight: ${totalWeight(shipment)} lb`);
console.log(`Boxes: ${countBoxes(shipment)}`);
Total weight: 15 lb
Boxes: 3
class Box {
pounds: number;
constructor(pounds: number) { this.pounds = pounds; }
}
class Pallet {
items: ShippingItem[];
constructor(items: ShippingItem[]) { this.items = items; }
}
// Anything that can go in a shipment.
type ShippingItem = Box | Pallet;
function totalWeight(items: ShippingItem[]): number {
let total = 0;
for (const item of items) {
if (item instanceof Box) { total += item.pounds; }
else if (item instanceof Pallet) {
for (const inner of item.items) {
if (inner instanceof Box) { total += inner.pounds; }
// A pallet on a pallet? Pallets didn't stack when this was written.
}
}
}
return total;
}
function countBoxes(items: ShippingItem[]): number {
let count = 0;
for (const item of items) {
if (item instanceof Box) { count++; }
else if (item instanceof Pallet) {
for (const inner of item.items) {
if (inner instanceof Box) { count++; }
}
}
}
return count;
}
const shipment = [new Box(5), new Pallet([new Box(8), new Box(2), new Pallet([new Box(2), new Box(5)])])];
console.log(`Total weight: ${totalWeight(shipment)} lb`);
console.log(`Boxes: ${countBoxes(shipment)}`);
Total weight: 15 lb
Boxes: 3
The tracker says 15 pounds and 3 boxes. The small pallet's two boxes, 7 pounds, were never counted, so the carrier was quoted for the wrong weight. The fix that comes to mind is a third loop inside the second, in both methods. Then someone stacks a pallet four deep.
- The symptom: "is it a box or a pallet?" checks, the same nesting copied into every method that walks a shipment, and one more loop for every level of pallets.
- The cause: the code treats one thing (a box) and a group of things (a pallet) as two different kinds, so every method has to know how deep the groups go.
What would you try?
Add a loop for each level, as deep as anyone stacks. Three levels today, and every method that walks a shipment (weight, box count, the label, the customs form) needs the same extra loop, and still has a limit.
Flatten every shipment into one list of boxes when it's packed. The weight comes out right, but the tracker no longer knows which boxes are on which pallet, and the forklift driver needs that.
Ban pallets on pallets. The customer who does it will ship with a carrier whose software can cope.
What we want is code that never asks "box or pallet?" at all, and doesn't care how deep the pallets go.
The fix: ask the same question of a box and of a pallet
A warehouse floor scale works this way. Roll a loaded pallet onto it and it gives one number, the weight of everything on it, however it's packed: boxes, a pallet on the pallet, boxes inside boxes. You don't weigh the parts and add them up yourself.

In code, a box and a pallet keep the same promise: each can answer "how much do you weigh?" and "how many boxes are you?". A box answers with its own weight, and 1. A pallet answers by asking each thing on it the same question and adding up the answers. When one of those things is itself a pallet, it does the same with its own things. The code that weighs a shipment asks.

List<IShippingItem> shipment = new List<IShippingItem>
{
new Box(5),
new Pallet(new List<IShippingItem> { new Box(8), new Box(2), new Pallet(new List<IShippingItem> { new Box(2), new Box(5) }) }),
};
Console.WriteLine( quot;Total weight: {shipment.Sum(item => item.Weight())} lb");
Console.WriteLine( quot;Boxes: {shipment.Sum(item => item.Boxes())}");
// The promise a box and a pallet both keep.
interface IShippingItem
{
int Weight();
int Boxes();
}
class Box : IShippingItem
{
private readonly int pounds;
public Box(int pounds) { this.pounds = pounds; }
public int Weight() => pounds;
public int Boxes() => 1;
}
class Pallet : IShippingItem
{
private readonly List<IShippingItem> items;
public Pallet(List<IShippingItem> items) { this.items = items; }
// A pallet asks each thing on it the same question, however deep it goes.
public int Weight() => items.Sum(item => item.Weight());
public int Boxes() => items.Sum(item => item.Boxes());
}
Total weight: 22 lb
Boxes: 5
// The promise a box and a pallet both keep.
interface ShippingItem {
int weight();
int boxes();
}
record Box(int pounds) implements ShippingItem {
public int weight() { return pounds; }
public int boxes() { return 1; }
}
record Pallet(List<ShippingItem> items) implements ShippingItem {
// A pallet asks each thing on it the same question, however deep it goes.
public int weight() {
int total = 0;
for (ShippingItem item : items) { total += item.weight(); }
return total;
}
public int boxes() {
int count = 0;
for (ShippingItem item : items) { count += item.boxes(); }
return count;
}
}
void main() {
List<ShippingItem> shipment = List.of(
new Box(5),
new Pallet(List.of(new Box(8), new Box(2), new Pallet(List.of(new Box(2), new Box(5))))));
int pounds = 0;
int boxes = 0;
for (ShippingItem item : shipment) {
pounds += item.weight();
boxes += item.boxes();
}
IO.println("Total weight: " + pounds + " lb");
IO.println("Boxes: " + boxes);
}
Total weight: 22 lb
Boxes: 5
# Both classes keep the same promise: weight() and boxes().
class Box:
def __init__(self, pounds):
self.pounds = pounds
def weight(self):
return self.pounds
def boxes(self):
return 1
class Pallet:
def __init__(self, items):
self.items = items
# A pallet asks each thing on it the same question, however deep it goes.
def weight(self):
return sum(item.weight() for item in self.items)
def boxes(self):
return sum(item.boxes() for item in self.items)
shipment = [Box(5), Pallet([Box(8), Box(2), Pallet([Box(2), Box(5)])])]
print(f"Total weight: {sum(item.weight() for item in shipment)} lb")
print(f"Boxes: {sum(item.boxes() for item in shipment)}")
Total weight: 22 lb
Boxes: 5
// Both classes keep the same promise: weight() and boxes().
class Box {
constructor(pounds) { this.pounds = pounds; }
weight() { return this.pounds; }
boxes() { return 1; }
}
class Pallet {
constructor(items) { this.items = items; }
// A pallet asks each thing on it the same question, however deep it goes.
weight() { return this.items.reduce((sum, item) => sum + item.weight(), 0); }
boxes() { return this.items.reduce((sum, item) => sum + item.boxes(), 0); }
}
const shipment = [new Box(5), new Pallet([new Box(8), new Box(2), new Pallet([new Box(2), new Box(5)])])];
console.log(`Total weight: ${shipment.reduce((sum, item) => sum + item.weight(), 0)} lb`);
console.log(`Boxes: ${shipment.reduce((sum, item) => sum + item.boxes(), 0)}`);
Total weight: 22 lb
Boxes: 5
// The promise a box and a pallet both keep.
interface ShippingItem {
weight(): number;
boxes(): number;
}
class Box implements ShippingItem {
pounds: number;
constructor(pounds: number) { this.pounds = pounds; }
weight(): number { return this.pounds; }
boxes(): number { return 1; }
}
class Pallet implements ShippingItem {
items: ShippingItem[];
constructor(items: ShippingItem[]) { this.items = items; }
// A pallet asks each thing on it the same question, however deep it goes.
weight(): number { return this.items.reduce((sum, item) => sum + item.weight(), 0); }
boxes(): number { return this.items.reduce((sum, item) => sum + item.boxes(), 0); }
}
const shipment: ShippingItem[] = [new Box(5), new Pallet([new Box(8), new Box(2), new Pallet([new Box(2), new Box(5)])])];
console.log(`Total weight: ${shipment.reduce((sum, item) => sum + item.weight(), 0)} lb`);
console.log(`Boxes: ${shipment.reduce((sum, item) => sum + item.boxes(), 0)}`);
Total weight: 22 lb
Boxes: 5
22 pounds and 5 boxes, and no method anywhere asks "box or pallet?". Stack a pallet ten deep and the same code weighs it. A new kind of thing to ship, a padded envelope, say, is one new class that keeps the same promise; nothing that weighs shipments changes.
Where the languages differ. C#, Java and TypeScript write the promise as an interface. Python and JavaScript need none: anything with a weight() and a boxes() method will do. Java's records make each class a few lines.
A pallet, as an object diagram
Here is the pallet at run time, as an object diagram: each box is an object, and so is each pallet. Read the weights from the bottom up. The small pallet asks its two boxes (2 and 5) and answers 7. The big pallet asks its three things (8, 2 and the small pallet's 7) and answers 17. Add the loose 5-pound box, and the shipment is 22.

The pallet's weight ends up calling weight again, on something smaller, until it reaches boxes. A method that solves a problem by handing a smaller piece of the same problem to the same method is called recursion. It isn't a trick; it's what happens when a pallet asks a pallet. It always stops, because every stack of pallets ends in boxes, and a box answers straight away. A shape like this, one thing at the top branching into things that branch again, is called a tree.
How it got its name
A pallet is composed of other things, and it can be treated as one thing. Code that lets a group answer the same questions as a single item follows the Composite pattern. It's in the original 1994 book, and it has no shorter, modern version: in every language it's an interface and two kinds of class.
Composite or Decorator?
Both hold objects that keep the same promise they keep themselves, so their diagrams look alike. What they're for tells them apart:
| Pattern | What it's for | Strengths | Weaknesses | Pick it when |
|---|---|---|---|---|
| Composite | Lets a group answer the same questions as a single item, by asking its parts | Code treats one box and a whole pallet alike, at any depth; a new kind of item is one class | A method that only makes sense for single items (open the box) sits awkwardly on a group | Things contain things of the same kind, and you ask questions of the whole |
| Decorator | Wraps one item and adds to its answer, keeping its promise | Adds a feature without changing the item; wrappers can be layered | Many small wrappers to follow; the order of the layers can matter | One item needs something extra, such as a padded box that adds 1 pound of padding to the box's weight (Pass 3) |
The quickest test: how many does it hold? A composite holds many and combines their answers. A decorator holds exactly one and changes its answer.
Where you've already used it
- Folders on your computer: a folder's size is the size of everything in it, folders included.
- A web page's elements: a
<div>holds elements that hold elements, and hiding thedivhides them all. - A to-do app's lists inside lists, where checking off a list checks off everything in it.
When not to use it
- When nothing nests. If a shipment is only ever a list of boxes, a loop over the boxes is clearer than an interface and two classes.
- When single items and groups need very different questions. If almost every method only makes sense for one of them, forcing them under one promise makes both awkward.
The cost: the code that walks the tree is short, but following one answer means following the calls down through every level.
How often you'll meet it: now and then in app code, and every day in the tools you use (our estimate: every folder, menu and web page is one).
Check yourself
2 questions to try on the lesson page.
So what
When code keeps asking "one thing, or a group of things?" and needs a loop for every level, let the group keep the same promise as the single thing. Then a question asked of the whole is answered all the way down, however deep it goes.