Composition
A whole that owns its parts: it creates them, nothing else holds them, and they end when it ends. Also the design habit of building behavior by combining objects instead of inheriting.
Overview
Composition is the strongest whole-part relationship. The whole creates its parts, keeps them private, and the parts have no life of their own. A house has rooms; when the house is demolished the rooms are gone. An order has line items; delete the order and the line items go with it. In UML this is a filled diamond at the whole.
The word is also used for a second, related idea: building an object's behavior by giving it other objects to delegate to, instead of inheriting from a base class. That is the 'composition' in 'favor object composition over class inheritance', a guideline from the Design Patterns book (Gamma, Helm, Johnson and Vlissides, 1994). Interviewers ask about both meanings, often in the same conversation, so this topic covers both and says which is which.
The whole owns the part
Five tests tell you a relationship is composition.
- Who creates the part? The whole, usually in its constructor.
- Who else holds the part? Nobody; it is a private detail of the whole.
- How many wholes can a part be in? At most one at a time (UML 2.5.1).
- What happens when the whole is deleted? Its parts are deleted with it (UML 2.5.1).
- How is it drawn? With a filled diamond at the whole.
Here is a house and its rooms in that notation.
The UML standard states the rule directly: a composite part may be included in at most one composite object at a time, and if the composite is deleted, its parts are deleted with it. It also allows a part to be removed from the whole before the whole is deleted, in which case the part survives. That detail is worth saying in an interview: composition is about who is responsible for the part, not a promise that the part can never move.
Interview questions
- Why is composition preferred over inheritance?
- How do you implement composition, and how does that differ from aggregation in code?
- If I inject the part through the constructor, is it still composition?
- What is the fragile base class problem, and how does composition avoid it?
- How does composition show up in UML and in a database schema?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio