Part 3 of 6 · 1 min read
A design choice
Add and remove on the interface or not.
GoF discusses a choice. Should add and remove be declared on the common interface, or only on the composite class? Putting them on the interface gives transparency: every node looks the same, but a leaf must either ignore the call or throw an error. Putting them only on the composite gives safety: the compiler stops you adding a child to a file, but a client must know which kind it holds before it adds a child.
The code above takes the safe route: add exists only on Folder. This matches the lesson of substitutability (Level 2, module 3): a method that a class cannot honour should not be on its interface.
Operations such as size are the happy case, since they apply naturally to both kinds. A folder does the work by asking each child.
Check yourself:
1. What is the benefit of putting add only on the composite?
2. What does a leaf do with add in the transparent design?