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
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
Relationships: Order β Item β Payment
Model an e-commerce Order to understand the three types of object relationships: Compositiβ¦
Library Management System
Design a library system where members can search, borrow, and return books. Librarians canβ¦
Movie Ticket Booking (BookMyShow)
Design a movie ticket booking platform with seat selection, concurrent booking safety, andβ¦
Inventory Management System
Design an inventory system for an e-commerce warehouse with stock tracking, reordering, anβ¦
Expense Splitter (Splitwise-like)
Design an app that tracks shared expenses and calculates who owes whom in a group.β¦
π Now apply what you learned
Pick a problem above, write your solution, and get AI feedback on your design.
Start Practice β