Aggregation
A whole that groups parts it does not own: the parts are created elsewhere, can be shared, and outlive the whole.
Overview
Aggregation is a whole-part relationship in which the whole does not own its parts. A team has players, a department has employees, a playlist has songs. The whole groups the parts and uses them, but it did not create them, it does not decide when they end, and it may share them with other wholes. When the team is disbanded, the players are still there.
That last sentence is the whole idea. Every other relationship question in a low level design interview comes back to one test: what happens to the part when the whole goes away? If the part survives, you have aggregation (or a plain association). If the part goes with it, you have composition.
Whole, part, and who owns whom
Object-oriented design names three kinds of link between classes. They differ in how tightly the lifecycles are tied.
- Association: it answers 'do these objects know about each other?'. The part outlives the whole and can be shared by several wholes. UML draws it as a plain line.
- Aggregation: it answers 'does this whole group these parts?'. The part still outlives the whole and can still be shared. UML draws a hollow diamond at the whole.
- Composition: it answers 'does this whole own these parts?'. The part does not outlive the whole and is not shared. UML draws a filled diamond at the whole.
So association and aggregation agree on both lifecycle questions; only composition says no to both. The class diagram below shows the hollow diamond on a team and its players.
Interview questions
- How is aggregation different from composition?
- How do you implement aggregation in code, and what does getting it wrong look like?
- When is aggregation the right call, and when is a plain association enough?
- Can one part belong to several wholes at the same time?
- How does aggregation map to 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