⚑LLD Hub
Learn

Object Relationships β€” Composition, Aggregation, Association

Composition: part dies with the whole. Β· Aggregation / association: looser lifecycles.

Watch

Watch, then scroll down for code and practice.

In code

Order owns line itemsTypeScript
class LineItem {
  constructor(public sku: string, public qty: number) {}
}

class Order {
  private items: LineItem[] = [];
  addItem(i: LineItem) {
    this.items.push(i);
  }
  // If Order is deleted, items go with it (composition).
}

πŸ“˜ Key ideas

Composition (strongest)

Part cannot exist without the whole. Order owns LineItems β€” delete the Order and LineItems go too. Use when lifecycle is bound.

Aggregation (medium)

Whole references the part, but the part can exist independently. Order aggregates Customer β€” delete the Order, Customer stays.

Association (weakest)

Objects know about each other but neither owns the other. Order uses Payment β€” both can exist independently.

Interview tip

When asked 'how do X and Y relate?', answer with the relationship type and justify the lifecycle decision. This shows depth of thought.

🧠 Practice β€” Apply What You Learned

πŸš€ Now apply what you learned

Pick a problem above, write your solution, and get AI feedback on your design.

Start Practice β†’