Aggregate Root
ELI5 — The Vibe Check
An aggregate root is the boss entity that controls a group of related objects. Want to add an item to an order? You don't talk to OrderItem directly — you go through the Order (the aggregate root). It enforces all the business rules for its cluster of objects.
Real Talk
In domain-driven design, an aggregate root is the entry point entity for a cluster of domain objects (aggregate) that are treated as a single unit for data changes. All modifications to objects within the aggregate must go through the root, which enforces invariants and consistency rules. External objects can only reference the aggregate root, not internal entities.
Show Me The Code
class Order {
private items: OrderItem[] = [];
addItem(product: Product, qty: number) {
if (this.items.length >= 50) throw new Error('Max 50 items');
if (this.status !== 'draft') throw new Error('Cannot modify shipped order');
this.items.push(new OrderItem(product, qty));
this.recalculateTotal();
}
}
When You'll Hear This
"Order is the aggregate root — all item modifications go through it." / "Never modify entities inside an aggregate directly; always use the root's methods."
Related Terms
Domain-Driven Design (DDD)
DDD says your code should speak the same language as the business.
Entity
An entity is a domain object with a unique identity that persists over time.
Repository Pattern
Repository Pattern puts a layer between your business logic and your database, so your business code never writes SQL directly.
Value Object
A value object is defined by its values, not its identity. Two $10 bills are interchangeable — you don't care which specific bill you have.