Aggregation vs composition
medium 45 minBoth say that an object has another one.
Video lesson · Chapter 1 of 6
Make a prediction
0:00 / 4:41
See it run
Let the whole go, and see what is left.
Operations
Students survive
Aggregation: the university only refers to its students.
Step 1 of 5
Students first
They exist before any university.
Step 1: Students first
asha, lee, noor = Student(), Student(), Student()university = University()for s in (asha, lee, noor): university.enroll(s)shop.hire(asha)del universityprint(asha.name)- Good for
- Shared, independent parts
- Costs
- Somebody else must end them
- Students removed
- 0
Shared by two wholes: it cannot be composition.
In the real world
The same aggregation vs composition doing real jobs. Pick one and step through it.
Throw the box away, tear the paper.
Step 1 of 4
Two wholes
A box with a brick, and paper with a drawn house.
Step 1: Two wholes
Common mistakes
The bugs interviewers watch for, with the fix beside each.
The live list goes out
criticalAnybody can change owned parts without a check.
Wrongdef lines(self): return self._linesRightdef lines(self): return tuple(self._lines)Price read live
criticalA price change rewrites old orders.
Wrongreturn line.product.cents * line.qtyRightreturn line.unit_cents * line.qtyCascade on known things
criticalOne deleted customer removes invoices.
Wrongcustomer_id REFERENCES customer(id) ON DELETE CASCADERightcustomer_id REFERENCES customer(id) ON DELETE RESTRICTStrong way back
majorCounters never reach zero.
Wrongstd::shared_ptr<Folder> folder;Rightstd::weak_ptr<Folder> folder;A deep copy of everything
majorThe person exists twice, and one is updated.
Wrongcopy.deepcopy(plan)RightPlan(Task(t.title, t.who) for t in tasks)
Interview tips
Four questions
- Who ends it?
- Who shares it?
- Who changes it?
- Who finds it?
Keep it owned
- Copy in, copy out
- The whole makes the parts
- No way back for callers
Draw it
- Diamond at the whole
- Add multiplicities
- No promise: plain line
In the room
- Use a pair from the problem
- Say what delete and copy do
- It depends: say on what