the concepts of aggregates, entities, and value objects using a simple example from the domain of e-commerce: an online shopping cart system.
-
Aggregates:
- Aggregates are clusters of domain objects that are treated as a single unit.
- They have a root entity, known as the aggregate root, which is responsible for maintaining consistency and enforcing invariants within the aggregate.
- Aggregates are defined based on transactional consistency boundaries.
- In our example, the shopping cart can be considered an aggregate. It consists of multiple items (entities) and has a root entity, the cart itself.
-
Entities:
- Entities are objects that have a distinct identity and are defined by their attributes and behavior.
- They represent domain concepts that are unique and are typically mutable.
- Entities often have a lifecycle and can be persisted in a database.
- In our example, each item in the shopping cart, such as a product, can be considered an entity. Each product has its own attributes (e.g., name, price, quantity) and behavior (e.g., adding/removing from cart).
-
Value Objects:
- Value objects are objects that represent a concept, but their identity is based on their attributes rather than being unique.
- They are immutable and are defined solely by their attribute values.
- Value objects are used for attributes that are interchangeable and can be compared based on their values.
- In our example, the price of each item in the shopping cart can be represented as a value object. The price itself doesn't have an identity; it's defined by its value (e.g., $10.99).
Here's how these concepts could be represented in code (using a hypothetical Java-like syntax):
// Value Object representing the price
public class Price {
private BigDecimal amount;
public Price(BigDecimal amount) {
this.amount = amount;
}
public BigDecimal getAmount() {
return amount;
}
// Other methods for operations on price
}
// Entity representing a product
public class Product {
private String productId;
private String name;
private Price price;
// Constructor, getters, setters, etc.
}
// Aggregate Root representing the shopping cart
public class ShoppingCart {
private List<Product> items;
public void addItem(Product product) {
// Logic to add item to cart
}
public void removeItem(Product product) {
// Logic to remove item from cart
}
// Other methods for cart operations
}
In this example, Price
is a value object representing the price of a product, Product
is an entity representing a product with a unique identity, and ShoppingCart
is an aggregate root representing the shopping cart, which contains multiple product entities as items.