How should you handle an operation, like adding a child, that only makes sense on composite nodes and not on leaves?
There are two common approaches, and both are legitimate trade-offs rather than one being universally correct. The first keeps the operation off the shared component interface entirely and defines it only on the concrete composite class, meaning leaf objects simply don't have the method at all -- this respects interface segregation, since no class is forced to expose an operation it can't meaningfully support, but it means client code needs to know it's holding a composite specifically before it can call that method. The second puts the operation on the shared interface for uniformity, and has leaf classes implement it by throwing an exception like UnsupportedOperationException -- every node looks identical from the outside, but callers can now hit a runtime error if they call it on the wrong kind of node. Which one to choose depends on whether uniform typing or compile-time safety matters more for the specific codebase.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response