Facebook Pixel

Composite Pattern

Treating files and folders the same way

A file system has two kinds of things: files and directories. A file has a size. A directory also has a size — the sum of everything inside it, which might include more directories. Code that wants to know how much space a path consumes should not need to care which kind it is holding.

Without a shared interface, every size calculation branches on type:

The Composite pattern gives File and Directory a shared interface.

1# Bad: every caller must branch on type to traverse the tree.
2def get_size(node):
3    if isinstance(node, File):
4        return node.size
5    elif isinstance(node, Directory):
6        total = 0
7        for child in node.children:
8            total += get_size(child)  # recursive type-check buried here
9        return total
10    else:
11        raise TypeError(f"unknown node type: {type(node)}")

The instanceof checks spread to every function that touches the tree: delete, rename, search. Adding a new node type — say, a symbolic link — requires hunting down every branch and adding another arm.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro