REQUIREMENTS & MODELING / OBJECT DESIGN BRIEF

Association, aggregation, and composition

These are three strengths of 'has-a' relationships.

BeginnerPhase 03 / Topic 7 of 8ResponsibilitiesCollaborationsExtensibility
01

Overview

These are three strengths of 'has-a' relationships. Association: one object knows and uses another, with independent lifecycles (a Doctor treats Patients). Aggregation: a whole contains parts that can exist independently and may be shared (a Team has Players). Composition: a whole owns its parts, which are created with it and destroyed with it (an Order has OrderLines).

The distinction drives code decisions: who creates the object, who is allowed to hold references, whether deleting the whole cascades to the parts, and whether parts can be shared. In code, composition usually means the whole constructs the parts internally and never exposes them for outside mutation.

A university

A professor is associated with students (they interact but live independently). A department aggregates professors (professors can move to another department). A building is composed of rooms (demolish the building and the rooms are gone).

02

When to use it

  • Drawing class diagrams.
  • Deciding object creation and ownership.
  • Designing deletion and cascading rules.
03

Where it shows up in interviews

Ownership decisions

Recognize it when: who creates and deletes what?

  • Design a library system
  • Design an order system
04

Where it is used in real software

ORM cascades

JPA's cascade and orphanRemoval, and database ON DELETE CASCADE, implement composition.

DDD aggregates

Aggregate roots compose their internal entities; other aggregates are referenced by ID (association).

UI trees

A window composes its widgets; closing it destroys them.

05

Key terms

Association
Uses/knows; independent lifecycles.
Aggregation
Whole-part, parts can exist alone or be shared.
Composition
Whole-part with exclusive ownership and shared lifecycle.
Dependency
Weakest link: uses temporarily (parameter or local).
06

How it works, step by step

  1. 1
    Ask: can the part exist without the whole?

    No: composition.

  2. 2
    Ask: can the part be shared among wholes?

    Yes: aggregation or association.

  3. 3
    Decide creation

    Composition: whole creates parts.

  4. 4
    Decide exposure

    Composition: expose copies or read-only views.

  5. 5
    Decide deletion

    Composition cascades; aggregation does not.

07

Classifying relationships

Examples from common LLD problems

Step 1 / 5
PairRelationshipWhy
Order - OrderLineCompositionLines have no meaning without the order
Team - PlayerAggregationPlayers exist and can change teams
Member - Loan (library)AssociationIndependent lifecycles, linked by activity
Chess Board - SquareCompositionSquares are created with the board
Car - DriverAssociationDrivers use many cars

NOWPair: Order - OrderLine | Relationship: Composition | Why: Lines have no meaning without the order

The question is always about lifecycle and ownership, not about how the objects look.

08

Implementation

// Composition: Order creates and owns its linesclass Order {  #lines: { sku: string; qty: number }[] = [];  addLine(sku: string, qty: number) { this.#lines.push({ sku, qty }); }  // created inside  get lines() { return this.#lines.map((l) => ({ ...l })); }              // never shared} // Aggregation: Team holds players created elsewhereclass Player { constructor(readonly name: string) {} }class Team {  private players = new Set<Player>();  add(p: Player) { this.players.add(p); }  remove(p: Player) { this.players.delete(p); } // player still exists} // Association: a Doctor references patients it treatsclass Patient { constructor(readonly id: string) {} }class Doctor {  treat(patient: Patient) { return `treating ${patient.id}`; }}
09

Complexity and performance

Cascade delete (composition)O(parts)

Parts go with the whole.

Shared parts (aggregation)No cascade

Reference removal only.

10

Trade-offs

Strict ownership vs flexibility

Composition protects invariants but prevents sharing; aggregation allows reuse but invites aliasing bugs.

UML nuance

Aggregation is often ambiguous; many teams just use association and composition.

11

Variants and related techniques

Reference by ID

Across aggregates, hold IDs rather than object references.

Weak references

Language-level references that do not prevent garbage collection.

12

Common mistakes

  • Exposing composed parts for external mutation.

    Fix: Return copies or read-only views.

  • Calling every has-a composition.

    Fix: Check lifecycle independence first.

13

Interview questions

Composition vs aggregation with an example?

Composition: an Order and its OrderLines; lines are created by the order and deleted with it. Aggregation: a Team and its Players; players exist independently and can join other teams.

How does composition show up in code?

The whole creates its parts internally, keeps them private, exposes only copies or behavior, and deletion of the whole removes the parts.

14

Practice problems

ProblemDifficultyWhat it trains
Classify 8 relationships in a hotel systemEasyLifecycle questions.
Model a chess board and piecesMediumComposition vs association.