AlgoViz

Aggregation vs composition

medium 45 min

Both 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

ashaStudentaliveyesleeStudentaliveyesnoorStudentaliveyes

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

boxhas bricksstateherebrickBrickplacein the boxpaperhas a drawingstatewholehouseDrawingstatedrawn

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

    critical

    Anybody can change owned parts without a check.

    Wrong
    def lines(self): return self._lines
    Right
    def lines(self): return tuple(self._lines)
  • Price read live

    critical

    A price change rewrites old orders.

    Wrong
    return line.product.cents * line.qty
    Right
    return line.unit_cents * line.qty
  • Cascade on known things

    critical

    One deleted customer removes invoices.

    Wrong
    customer_id REFERENCES customer(id) ON DELETE CASCADE
    Right
    customer_id REFERENCES customer(id) ON DELETE RESTRICT
  • Strong way back

    major

    Counters never reach zero.

    Wrong
    std::shared_ptr<Folder> folder;
    Right
    std::weak_ptr<Folder> folder;
  • A deep copy of everything

    major

    The person exists twice, and one is updated.

    Wrong
    copy.deepcopy(plan)
    Right
    Plan(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