SOLID & Design Patterns Interview Question #71
What is an Aggregate in Domain-Driven Design?
Advanced Patterns, CQRS & Domain-Driven Design Fundamentals Mid-Level Intermediate
Quick Interview Answer
An aggregate is a consistency boundary containing one or more domain objects that are treated as a unit for business changes. External code interacts with the aggregate through its root.
Detailed Explanation
An aggregate is a consistency boundary containing one or more domain objects that are treated as a unit for business changes. External code interacts with the aggregate through its root.
The aggregate protects invariants so related state changes remain valid. Aggregates should be designed around transactional consistency requirements rather than simply mirroring database relationships.
Code Example
public class Order
{
private readonly List<OrderItem> _items = new();
public IReadOnlyCollection<OrderItem> Items
=> _items;
public void AddItem(Product product, int quantity)
{
// Enforce order invariants here.
}
}