A rich domain model puts business rules and behavior inside domain objects instead of leaving them as data containers. An Order, for example, can calculate its own total and apply a customer discount, keeping that logic close to the data it governs. section 4.7.3
The pattern makes domain objects responsible for:
- Calculating business values, such as an order total from item prices and quantities, including any eligible discount. section 4.7.3
- Keeping controllers thin and application services focused on orchestration, rather than scattering domain rules across them. section 4.7.3
Listing 4.9 Creating the Rich Domain Model
class Order
{
private const decimal GOLD_DISCOUNT_RATE = 0.9m;
public int Id { get; set; }
public decimal Total { get; private set; } #A
// The order “knows” its customer
public Customer Customer {get; private set; } #A
public string CustomerEmail => Customer.Email #B
// Encapsulated collection to prevent external mutation
private readonly List<Item> _items = new List<Item>();
public IReadOnlyList<Item> Items => _items.AsReadOnly(); #C
// Expression-bodied members for calculated data
public bool IsEligibleForDiscount => Customer != null &&
Customer.Type == "Gold";
// The Atomic Truth: Logic and data are now perfectly unified.
public decimal TotalPrice => _items.Sum(i => i.Price * i.Quantity) #D
* (IsEligibleForDiscount ? GOLD_DISCOUNT_RATE : 1);
public Order(Customer customer)
{
Customer = customer ?? throw new ArgumentNullException( #E
nameof(customer));
Id = new Random().Next(1000, 9999);
}
public void AddItem(Item item) #F
{
if (item.Price <= 0)
{
throw new InvalidOperationException("Item price" +
"must be positive.");
}
_items.Add(item);
}
}The Order example shows a calculated total, Gold-customer discount eligibility, and an encapsulated item collection. section 4.7.3
This approach helps keep business logic maintainable and testable, but it works as part of a broader architecture: domain contracts and infrastructure implementations are kept in separate layers. Automated architectural tests can help preserve those boundaries as the system changes. section 4.10 section 4.7.4
