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

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

  1. 1976

    Peter Chen's entity relationship model has weak entities: rows that cannot be identified without their owner.

  2. 1997

    UML is adopted as a standard by the Object Management Group, with filled and hollow diamonds.

  3. 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.

  4. 2011

    C++11 adds unique_ptr, shared_ptr and weak_ptr to the standard library: ownership becomes part of a type.

  5. 2015

    Rust 1.0 makes single ownership a rule that the compiler checks for each value.

  6. 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.

The castle and the tide

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

AggregationComposition
MeaningHas, weakHas, strong: owns
OwnerSomebody elseThe whole, exactly one
LifeIndependentEnds with the whole
Usually createdOutside, and passed inInside, or handed over completely
SharedAllowedNot allowed
UMLHollow diamond at the wholeFilled diamond at the whole
Java, Python, TypeScriptA reference others have tooA private reference that does not leak
C++Reference, raw pointer, weak_ptr, sometimes shared_ptrDirect member, unique_ptr, container of values
DatabaseForeign key with RESTRICT or SET NULLForeign key with CASCADE, or columns in the same row
Copying the wholeCopies the referenceCopies the part

Hollow diamond: a university and its students

Student+ name: str

1/3Students first

Asha, Lee and Noor exist. No university made them.

has (lives on)

The diamond sits at the one who has.

Filled diamond: a body, a house, an order

11Human- heart: Heart- brain: BrainHeartBrain

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)

Cancel the order: the lines go, the lamp stays in the catalogue.

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

Python
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")       # gone
The smallest test: let the whole go, and ask for the part through a weak reference, which keeps nothing alive.
Edit and run it in your browser

The test

Four questions

  1. 1

    Who ends it?

    When the whole is deleted, must the part be deleted? This question decides.

  2. 2

    Who shares it?

    Can two wholes have the same one at the same time? If yes, it is not composition.

  3. 3

    Who changes it?

    If a rule of the whole depends on the part, the whole should own it.

  4. 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?

Creation is missing here on purpose. A part may be created outside and handed over, and it is then owned.

Examples, with the reason

PairRelationIt depends on
Team, playersAggregationPlayers can be traded
Library, booksAggregationBooks can move to another branch
Playlist, songsAggregationOne song in many playlists
Cart, productsAggregationProducts are in the catalogue
Cart, cart linesCompositionA line means nothing without its cart
Company, employeesAggregationPeople work elsewhere later
House, roomsCompositionA demolished house has no rooms
House, furnitureAggregationFurniture moves
Document, paragraphsCompositionIn an editor. With shared text blocks: aggregation
Email, attachmentsCompositionIf stored per mail. If many mails share one stored file: the reference is owned, the file is not
Car, engineBoth are rightA showroom: composition. A workshop that swaps engines: aggregation
Human, heartCompositionIn a game. In a transplant clinic a heart is moved
The same pair changes with the program. Do not learn the list: ask the questions for your own domain.

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.

Sources