Aggregation vs composition
medium 45 minBoth say that an object has another one.
Video lesson · Chapter 1 of 6
Make a prediction
Aggregation vs composition
1:00Reel
Theory
Read or listen first. About 2 min.
What it is
An object often has other objects. Composition is the strong form: the part belongs to exactly one whole, the whole is responsible for it, and the part is removed with the whole. An order and its lines, a house and its rooms.
Aggregation is the weak form: the whole refers to parts that have a life of their own. A part can be in several wholes or in none, and it stays when a whole goes. A team and its players, a playlist and its songs.
In UML both have a diamond at the whole: filled for composition, hollow for aggregation. UML defines composition exactly and leaves the details of shared aggregation to the modeller, so many teams draw a plain line for it.
Why it exists
The question is not academic. It decides who may delete, who may change, whether a part can be shared, what a copy must copy, and what the database does when a row disappears.
Wrong in one direction, you delete things that others need: closing a course erases its students. Wrong in the other, you leave things that nobody needs: order lines without an order, memory without an owner.
It also protects rules. If an order owns its lines, only the order can change them, so the total is always right. A line that others can reach and change makes that impossible.
A short history
1976
Peter Chen's entity relationship model has weak entities: rows that cannot be identified without their owner.
1997
UML is adopted as a standard by the Object Management Group, with filled and hollow diamonds.
2003
Eric Evans describes aggregates in Domain-Driven Design: a cluster of objects that is changed through one root. The word differs from UML aggregation: inside is mostly composition.
2011
C++11 adds
unique_ptr,shared_ptrandweak_ptrto the standard library: ownership becomes part of a type.2015
Rust 1.0 makes single ownership a rule that the compiler checks for each value.
2017
UML 2.5.1 is published (December), the version in use today.
Words to know
- Whole
- The object that has the part. The diamond is on its side.
- Part
- The object that is had.
- Owner
- The one responsible for creating, or receiving, and for ending a part.
- Life cycle
- From creation to removal. Composition binds the part's end to the whole's end.
- Exclusive
- At most one whole at a time.
- Multiplicity
- How many: 1, 0..1, 0..*, 1..*.
- Cascade
- Deleting the whole deletes the parts.
- Orphan
- A part whose whole is gone.
- Dangling reference
- A reference to something that has been removed.
- Escape
- An owned part is handed out so that others can change it.
- Aggregate root
- In domain-driven design, the only object through which a cluster is changed.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
Understand it
Start here
Sand towers and borrowed toys
Noor builds a sandcastle on the beach. Some of its parts are made of the castle. Others are only borrowed for it. The tide will show which is which.
Frames 2, 5 and 7 are composition, 1, 3, 4 and 6 are aggregation, and 8 is the question that aggregation leaves open.
Side by side
The two relations
| Aggregation | Composition | |
|---|---|---|
| Meaning | Has, weak | Has, strong: owns |
| Owner | Somebody else | The whole, exactly one |
| Life | Independent | Ends with the whole |
| Usually created | Outside, and passed in | Inside, or handed over completely |
| Shared | Allowed | Not allowed |
| UML | Hollow diamond at the whole | Filled diamond at the whole |
| Java, Python, TypeScript | A reference others have too | A private reference that does not leak |
| C++ | Reference, raw pointer, weak_ptr, sometimes shared_ptr | Direct member, unique_ptr, container of values |
| Database | Foreign key with RESTRICT or SET NULL | Foreign key with CASCADE, or columns in the same row |
| Copying the whole | Copies the reference | Copies the part |
Hollow diamond: a university and its students
1/3Students first
Asha, Lee and Noor exist. No university made them.
has (lives on)
Filled diamond: a body, a house, an order
1/3Made with the whole
In this model a human creates heart and brain in the constructor, and nobody else can reach them.
owns (dies together)has (lives on)
How it works
Two lives in pictures
Aggregation: the student was there before and stays after
Composition: the line lives inside the order's life
import weakref, gcclass Student: passclass University: def __init__(self): self.students = [] def enroll(self, s): self.students.append(s)class Heart: passclass Human: def __init__(self): self._heart = Heart()asha, uni = Student(), University()uni.enroll(asha)john = Human()student_ref, heart_ref = weakref.ref(asha), weakref.ref(john._heart)del uni, johngc.collect()print("student:", "alive" if student_ref() else "gone") # aliveprint("heart:", "alive" if heart_ref() else "gone") # goneThe test
Four questions
- 1
Who ends it?
When the whole is deleted, must the part be deleted? This question decides.
- 2
Who shares it?
Can two wholes have the same one at the same time? If yes, it is not composition.
- 3
Who changes it?
If a rule of the whole depends on the part, the whole should own it.
- 4
Who finds it?
Do people search for the part on its own? Then it has an identity and probably its own life.
Filled, hollow, or just a line?
Examples, with the reason
| Pair | Relation | It depends on |
|---|---|---|
| Team, players | Aggregation | Players can be traded |
| Library, books | Aggregation | Books can move to another branch |
| Playlist, songs | Aggregation | One song in many playlists |
| Cart, products | Aggregation | Products are in the catalogue |
| Cart, cart lines | Composition | A line means nothing without its cart |
| Company, employees | Aggregation | People work elsewhere later |
| House, rooms | Composition | A demolished house has no rooms |
| House, furniture | Aggregation | Furniture moves |
| Document, paragraphs | Composition | In an editor. With shared text blocks: aggregation |
| Email, attachments | Composition | If stored per mail. If many mails share one stored file: the reference is owned, the file is not |
| Car, engine | Both are right | A showroom: composition. A workshop that swaps engines: aggregation |
| Human, heart | Composition | In a game. In a transplant clinic a heart is moved |
Pictures to keep
Box of bricks
Aggregation. Bricks go into another box, and they stay when the box is thrown away.
Drawing on paper
Composition. Tear the paper, and the drawing is torn.
House and sofa
Aggregation. Sell the house and take the sofa along.
House and walls
Composition. Nobody takes the walls along.
Traps
Where the difference is lost
Owned and kept
lines()returns a copy or a read-only view- The part has no public setters
- Only the whole creates parts
- Copying the whole copies the parts
Owned on paper only
getLines()returns the list itself- The caller keeps the object it passed in
- Two wholes got the same part
- A cascade on something that others need
Related pages: IS-A and HAS-A for the first choice, Proper encapsulation for copies on the way out, UML class diagrams for all signs, and Destructors and finalizers for what happens at the end of a life.
Summary
The whole topic in one minute.
Composition: one owner, the part ends with the whole. Aggregation: a reference, the part lives on. Filled and hollow diamond, at the whole.
Ask four questions: who creates it, who may share it, who may change it, who deletes it. Creation alone does not decide.
In code the difference is private lists, no shared references, copies on the way out. In C++ and Rust it is a type. In a database it is the delete rule.
- Composition: one owner, the part ends with the whole. Filled diamond.
- Aggregation: a reference, the part lives on, may be shared. Hollow diamond.
- The diamond sits at the whole.
- Deletion decides. Creation is only a hint.
- Ownership is kept by not letting references escape.
- The same pair can be either one: it depends on the program.