intermediate

Composite

Treat leaves and groups through one interface when clients should traverse or operate on a tree uniformly.

Composite lets clients treat individual objects and groups uniformly through a shared component interface—file systems, UI trees, org charts, scene graphs. Operations like render, sum, validate, or export recurse through children without `instanceof` ladders everywhere.

On interviews: explain when recursion belongs in composite nodes versus external visitors. Mention immutability for undo-friendly trees.

Common pitfalls: cycles in parent-child links; inconsistent invariants between leaves and containers; exposing mutable child lists publicly.

The trade-off is flexibility versus complexity—know when the simpler path is enough.

Checklist:

  • Leaf and composite implement same interface.
  • Container enforces child invariants centrally.
  • Traversal strategy is explicit (depth-first, breadth-first).
  • Tests cover empty composites and deep nesting.