Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Composition
LLD

Composition

Understand strong whole-part relationships and lifecycle ownership between objects.

The Problem It Distinguishes

A House has rooms. Demolish the house — the rooms cannot be toured, sold, or moved; they stop existing as rooms. This exclusivity (one whole owns each part, part’s lifetime bounded by whole’s) is composition — the strongest whole–part bond, and the one whose mishandling produces dangling references and leaked state in code.

         House                          Room
      ┌──────┐   filled diamond      ┌──────┐
      │ House│◆──────────────────────│ Room │
      └──────┘  (exclusive ownership) └──────┘
        house destroyed → rooms destroyed with it;
        a room belongs to exactly one house

Filled diamond = ownership of lifetime. Contrast aggregation’s hollow diamond where parts survive independently.

Java Mechanics

class House {
    private final List<Room> rooms;

    House(int roomCount) {
        rooms = new ArrayList<>();
        for (int i = 0; i < roomCount; i++)
            rooms.add(new Room(i));     // WHOLE creates its own parts
    }
    // no setter exposing the list; no constructor accepting external rooms:
    // both would break exclusive ownership
    List<Room> getRooms() { return List.copyOf(rooms); }  // read-only view
}

Two enforcement points: creation happens inside (new Room(...)), and exposure is restricted (List.copyOf prevents callers from removing parts behind the owner’s back).

Consequences That Follow From Ownership

  • Deletion: destroying the whole destroys parts — in code, dropping the last reference suffices if parts aren’t referenced elsewhere (which exclusive ownership guarantees); in databases, ON DELETE CASCADE.
  • Copying: deep copy required — copying the house must copy rooms, or two houses share walls:
House(House other) {
    this.rooms = other.rooms.stream().map(Room::new).collect(toList());
}
  • Equality: composed parts participate in the whole’s equality — two houses are equal only if their rooms match.

Where It Appears

  • Order ↔ OrderLine: delete order, line items go with it.
  • Document ↔ Paragraphs.
  • Invoice ↔ InvoiceItems.
  • Game character ↔ inventory slots (character-scoped items).

The Boundary Question

Real domains blur edges: can an OrderLine ever move to another Order (“transfer”)? If yes, lines are aggregations of a fulfillment system even if compositions of an order document. Decide per lifecycle question, not by intuition.

Composition vs Aggregation Recap

Aggregation ◇Composition ◆
OwnershipReference heldLifetime owned
Part countShareable across wholesExactly one whole
Whole deletedParts persistParts die
Copy semanticsShallow naturalDeep required
Constructor patternInject externallyCreate internally

Interview Signals

  • Answering “aggregation or composition?” with the deletion question instead of gut feel is the experienced tell.
  • Mentioning copy-constructor implications unprompted signals production experience — shared-mutable-part bugs from shallow copies are a recurring real-world defect class.

My Private Notes

Notes are auto-saved locally to this device.