Tactical Patterns
Having explored the key strategic patterns in the previous chapter, we now shift our focus to the tactical patterns of DDD. The patterns we will cover include entities, value objects, aggregates, repositories, services, and modules.
We will conclude the chapter with an in-depth analysis of events, in which we will discuss their significance. We will clarify the distinctions between domain events and integration events, ensuring you grasp their importance and correct application in DDD.
By the end of this chapter, you will have a comprehensive understanding of these tactical patterns and their critical role in effective DDD.
In this chapter, we will cover the following topics:
- Understanding tactical patterns in DDD
- Services and modules
- Domain and integration events
Technical requirements
Starting in this chapter, we will begin incorporating code examples to illustrate the tactical patterns of DDD in a practical context. The code will be written in C#, and while an in-depth knowledge of the language is not mandatory, having a basic understanding will greatly enhance your ability to follow along and comprehend the examples more swiftly.
For those unfamiliar with C#, even a basic grasp of its syntax and core concepts will be beneficial. However, if you are proficient in other programming languages, you should still be able to follow along and understand the examples with ease.
Throughout the book, we will refer to an example application to demonstrate the practical implementation of the concepts discussed. You can access the complete code for this example application on GitHub at the following URL: https://github.com/PacktPublishing/Domain-driven-Refactoring/branches . This repository will serve as a valuable resource throughout the rest of the book, allowing you to explore the code in detail and experiment with the patterns we cover.
By the end of this chapter, and as you progress through the book, you will not only gain theoretical knowledge but also practical skills in applying DDD principles using C#. This hands-on approach will solidify your understanding and prepare you to tackle real-world challenges in your software development refactoring.
Understanding tactical patterns in DDD
If the purpose of the strategic pattern is to identify the boundaries to split our domain into many subdomains, the purpose of the tactical pattern is to identify the components inside each bounded context.
In this section, we will cover the tactical aspects of DDD, where different patterns play distinct roles depending on the complexity and strategic importance of the subdomain. We must remember that not all subdomains are created in the same way. Different subdomains have different levels of complexity and different strategic importance. If you are writing code for a generic subdomain, you most likely do not need any special patterns. Sometimes, create, read, update, and delete ( CRUD ) is more than enough! A model that represents the table in your database is enough, and the use of an object-relational mapper ( ORM ) is sometimes helpful.
But what happens if you have to write code for your core subdomain? In this case, you need to have a model that represents your business problem—not just a collection of properties. A model composed of only properties is called an anemic domain , and this should not be your goal. A domain model has to be a full business model, with properties and behaviors. It has to be consistent from the moment it is instantiated and has to remain consistent in all its states. This consistency is upheld by enforcing business rules, invariants, and transactions, all of which must be guaranteed and protected for the entire lifespan of your domain model.
Take, as an example, our ERP for managing a brewery, and particularly our core subdomain, Sales . The flow to create a new sales order has to satisfy the following constraints, and many others:
- The customer should be able to create a new order. They should have enough credit to do that.
- The beers must be available in our warehouse or, at least, we should be able to restock them reasonably quickly.
- The delivery address should be valid and within the delivery area.
The domain model we create must implement behaviors to verify each of the preceding conditions. As you can see, a sales order has many objects and is a useful way to introduce some tactical patterns, which we are going to cover in the following sections.
Entities
An entity is an object that is primarily defined by a unique identifier, often referred to as its identity . This identity distinguishes one entity from another, even if their other attributes are identical. For example, in a business domain, a customer might be uniquely identified by a customer ID or a government-issued identifier such as a social security number.
What makes entities special is their life cycle: they are created, modified, and eventually deleted, but their identity remains constant throughout. Even if their details (such as a customer’s address or phone number) change, the entity itself remains the same as long as its identity is preserved.
Unlike a value object, which we will analyze shortly, the attributes of an entity can change over time. For example, a customer’s address or contact information may change but the customer remains the same entity.
Entities are persisted in storage systems such as databases. This persistence ensures that the state of the entity can be retrieved and maintained across the different sessions or uses of the application.
In our sales order, the object that contains the data of the order, such as customer data, order and delivery date, and the payment attribute, represents an entity. We will see that the sales order entity also contains the methods to implement the behavior of our business because we shouldn’t create an anemic domain.
The following code shows an example of an entity in our ERP. We use the library named Muflone ( https://github.com/CQRS-Muflone/Muflone ), which we wrote to support us, and we will get into it in the following chapters. For the moment, assume that Entity is just a base class with basic properties, such as Id :
public class SalesOrderRow : Entity
{
internal BeerId _beerId;
internal BeerName _beerName;
internal Quantity _quantity;
internal Price _beerPrice;
protected SalesOrderRow()
{
}
}
The first thing you will notice is that the SalesOrderRow class implements the base class, Entity .
Secondly, you can see that the property types are not primitive types (e.g., int or decimal ) but custom types that come from the ubiquitous language. We cannot stress enough that it is very important to share decisions about the behavior of this object with everyone who is working on it.
Finally, all the properties are declared internal because only the methods inside this namespace are allowed to change their values.
This encapsulation enforces a clear separation between the internal state of the entity and external access. An entity is defined not just by its properties but, more importantly, by the behaviors that operate on those properties.
If you’re wondering how application services can access these properties, the answer is: they can’t. Instead, a component within the domain (such as a mapper) is responsible for transforming entities into data transfer objects ( DTOs ). These DTOs are then used by the external layers of the application, preserving the integrity of the domain. Direct exposure of domain objects to external layers would break the principle of encapsulation and could lead to unwanted dependencies.
An entity in DDD is a core concept that emphasizes the importance of a unique identity. This identity remains constant even as the entity’s attributes change, making entities suitable for representing objects that need to be tracked individually throughout their life cycle. Understanding entities helps with designing systems that accurately reflect the uniqueness and persistence of real-world objects, ensuring that the business logic can manage these objects’ states and identities consistently.
Value objects
A value object is defined by its attributes rather than a unique identity. Two value objects are considered equal if all their attributes match, regardless of their location or instance within the system. This lack of identity makes them ideal for representing descriptive concepts in the domain, such as an address or a monetary amount.
A key characteristic of value objects is immutability: once they have been created, their state cannot be changed. If you need to modify a value object, you create a new instance with the updated attributes. This immutability ensures consistency and thread safety, as the state of a value object cannot be altered unexpectedly.
Value objects are typically short-lived and easily replaceable as they describe properties rather than tracking specific instances. For example, an address in a sales order is a value object because the system doesn’t need to uniquely identify that address; it only cares about its descriptive attributes.
In DDD, distinguishing between a value object and an entity depends on context. Use a value object when the identity is irrelevant and the focus is on attributes:
- An address in an order is a value object because its attributes (e.g., street and city) define its value and it doesn’t need a unique identity
- A customer , on the other hand, is an entity because it has a unique identifier (e.g., customer ID) that persists over time, even if its properties, such as the address, change
This distinction has practical implications. If a customer’s address changes, the old value object can be discarded and a new one created. Since value objects lack unique identities, there’s no need to maintain or track the old instance.
When designing a system, it is crucial to decide whether a concept should be modeled as a value object or an entity. This decision affects how you manage persistence, how you handle equality checks, and how you design the overall data model.
The following code is an example of a value object. Just as entities inherit from a common Entity base class, value objects inherit from a ValueObject base class. This allows you to avoid rewriting shared logic for each value object in your code base:
public class Price(decimal value, string currency) : ValueObject
{
public readonly decimal Value = value;
public readonly string Currency = currency ?? throw new NotImplementedException(nameof(currency));
protected override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
yield return Currency;
}
}
We want to reiterate that the big difference between an entity and a value object is that the former needs to have an ID, while the latter has no ID because it is defined by its attributes.
Notice also that each attribute is readonly . That is because a value object is an immutable object, which means if you need to modify it, you have to replace it with a new one.
Value objects are crucial in DDD for representing concepts that can be defined entirely by their attributes, without needing a unique identity. They are immutable, defined only by their attributes, and are often used to describe aspects or characteristics of entities. Understanding the difference between value objects and entities aids in building a clear and consistent domain model, ensuring that the system accurately represents the real-world processes it supports.
Aggregates
An aggregate is a group or cluster of domain objects, which can include entities and value objects. These domain objects are logically related and are treated as a single unit for the purpose of data changes. This means that changes to the state of any part of the aggregate are considered changes to the whole aggregate.
The aggregate has a special entity known as the aggregate root . This aggregate root serves as the entry point for accepting and interacting with the objects within the aggregate. It controls all access to the internal objects, ensuring that the integrity and invariants of the aggregate are maintained. The aggregate root is the only object that can be directly referenced from outside the aggregate.
Enforcing that all interactions go through the aggregate root, which encapsulates the internal structure and logic of the aggregate, helps maintain consistency, as the aggregate root can enforce business rules and constraints.
Aggregates define a consistency boundary. Within this boundary, all changes are made together in a single transaction. This means that the aggregate as a whole is always in a consistent state, even if some parts of it change.
Defining appropriate aggregate boundaries is crucial in DDD. Aggregates should not be too large, which can lead to performance and complexity issues, nor too small, which can lead to consistency problems. The goal is to encapsulate related changes and maintain consistency within the aggregate.
Since all changes within an aggregate are made in a single transaction, it’s important to design aggregates that can efficiently maintain this consistency without compromising performance. This often involves trade-offs between strong consistency and the scalability of the system.
Figure 4 .1 shows the relationships between aggregates. You can see that the entities of an aggregate may only link to the aggregate root of other aggregates. Relationships between entities in different aggregates that are not defined as aggregate roots are not permitted!
Figure 4 .1 – Aggregates
Now, let’s move our attention to the SalesOrder aggregate of our ERP by looking at the following piece of code:
public class SalesOrder : AggregateRoot
{
internal SalesOrderNumber _salesOrderNumber;
internal OrderDate _orderDate;
internal CustomerId _customerId;
internal CustomerName _customerName;
internal IEnumerable<SalesOrderRow> _rows;
protected SalesOrder()
{
}
internal static SalesOrder CreateSalesOrder(SalesOrderId salesOrderId, Guid correlationId, SalesOrderNumber salesOrderNumber,
OrderDate orderDate, CustomerId customerId, CustomerName customerName, IEnumerable<SalesOrderRowJson> rows)
{
return new SalesOrder(salesOrderId, correlationId, salesOrderNumber, orderDate, customerId, customerName,
rows);
}
private SalesOrder(SalesOrderId salesOrderId, Guid correlationId, SalesOrderNumber salesOrderNumber, OrderDate orderDate,
CustomerId customerId, CustomerName customerName, IEnumerable<SalesOrderRowJson> rows)
{
// Check SalesOrder invariants
}
}
The SalesOrder class derives from the AggregateRoot base abstract class so that everyone knows this is the entry point for the SalesOrder aggregate. The goal of this object is to maintain the integrity of SalesOrder as a whole, starting from its creation.
Also, all subsequent changes of status are the responsibility of this object, which exposes the method to implement the business behaviors. These methods can be reached through domain services or command handlers, depending on the pattern you used to implement the aggregate, but you can see all these cases shortly in this chapter.
An aggregate in DDD is a key concept that organizes related domain objects into a cohesive unit. The aggregate root is the only part of the aggregate accessible from outside, ensuring encapsulation and consistency. Aggregates define transaction boundaries, which are crucial for maintaining the integrity of the system’s state. By managing how domain objects are accessed and modified, aggregates help enforce business rules and invariants, providing a robust structure for complex business logic.
Repositories
The repository pattern acts as an intermediary between the domain model and the data mapping layers. It provides a way to manage access to the data source and ensures that the domain model remains independent of the underlying data access implementation.
It provides an abstraction layer over the data access mechanism and hides the details of data storage, retrieval, and mapping, thus allowing the domain model to focus solely on the business logic. This also decouples the domain layer from the data access, promoting a clean separation of concerns.
The purpose of the repository is to provide an interface for accessing aggregates from a data store. It handles CRUD operations and hides the implementation details of the data source.
In this pattern, a repository interface is defined that includes methods for retrieving and storing objects. For example, a repository interface for the SalesOrder aggregate might look like this:
public interface ISalesOrderRepository
{
SalesOrder GetById(Guid id);
IEnumerable<SalesOrder> GetAll();
void Add(SalesOrder salesOrder);
void Update(SalesOrder salesOrder);
void Remove(SalesOrder salesOrder);
}
This interface provides a contract for data access operations without exposing details about the underlying implementation.
The implementation of the repository interface will vary depending on the data source.
There are many benefits of using the repository pattern, starting with decoupling. The repository pattern decouples the domain logic from data access, allowing the domain object to focus solely on business logic. Using repository interfaces makes it straightforward to replace the data access layer with a mock or stub, facilitating the writing of unit tests. Thinking of the main goal of our exploration (refactoring), the repository centralizes data access logic, making it easier to maintain and modify your code after introducing it. That is possible because the repository ensures consistent handling of data access operations across the application, promoting a single source of truth for data access.
To conclude, repositories are used to manage aggregates rather than individual entities, as aggregates represent the consistency within a domain model. The design of the repository and the domain model should reflect the domain’s needs, not the underlying data storage mechanisms. Often, the unit of work pattern is used alongside repositories to manage transactions and ensure the atomicity of operations.
Unit of work
A unit of work manages a list of objects impacted by a business transaction and coordinates saving changes and resolving concurrency issues.
Factories
The factory pattern is a creational design pattern used in DDD to encapsulate the creation logic of aggregates. The primary purpose of the factory pattern is to provide a way to create objects without exposing the instantiation logic to the client and to ensure that the created objects are in a valid state. By centralizing creation logic in a factory, you maintain consistency, reduce duplication, and encapsulate the construction process.
Creating an aggregate involves complex validation or setting up a graph of objects. A factory can encapsulate this complexity and ensure that the created aggregates always satisfy the business rules and constraints defined in the domain model. By using a factory, you ensure that the objects are always created in a consistent and valid state, preventing inconsistencies that might arise from ad hoc object creation.
Why do you have to use this pattern? Because, like the repository pattern, the factory pattern has many benefits. First, the factory provides a single point to enforce business rules during the creation of objects, ensuring that all created objects are valid. When aggregate creation logic changes, it only needs to be updated in one place, the factory, rather than throughout the application. This is possible because aggregate construction processes, especially those involving the setup of dependencies or state, are abstracted away from the client. To conclude, the factory can be mocked or stubbed in unit tests, allowing more controlled and isolated testing scenarios.
Factories should only be responsible for creating aggregates, not for complex domain logic. They should not perform tasks beyond object creation, such as coordinating activities or managing transactions. The methods in a factory should use terms from the ubiquitous language, making it clear what the factory creates and what parameters are required.
The primary goal of a factory is to ensure that the created aggregates are always in a valid state, adhering to the business rules and constraints of the domain. A good practice is to keep the constructor of entities private or protected and use factory methods for object creation. This ensures that the factory controls the instantiation process, working directly with the aggregate root to maintain the integrity and invariants of the entire aggregate.
While factories ensure that aggregates are created in a consistent and valid state, they do not handle complex domain operations or cross-cutting concerns. This is where services come into play, providing a structured way to encapsulate domain logic that does not naturally belong to an entity or a value object.
Services and modules
In DDD, services and modules play a pivotal role in maintaining the clarity and separation of concerns within your application. Understanding the distinction between domain services and application services is crucial for architecting a robust and maintainable system.
Let’s start with services and see what the two types of service are, the differences between them, and when to use them. As usual, this exploration will be illustrated by examples in the domain of our brewery ERP.
Domain services
Domain services are an integral part of the domain model, encapsulating business logic that doesn’t naturally fit within an aggregate. They are used when a particular operation or process spans multiple entities or when the behavior does not belong to any specific entity. Domain services are pure, meaning they do not have side effects and typically do not rely on external systems such as databases or messaging systems.
Consider the brewery ERP system. Imagine you need to calculate the total price of a sales order, including various discounts and taxes. This calculation involves multiple entities and value objects, such as SalesOrder , Customer , Product , and Discount . Placing this logic inside any single entity would violate the Single Responsibility Principle ( SRP ) and make the entity unnecessarily complex. Instead, you would create a domain service, PricingService , to handle this calculation:
public class PricingService {
private readonly TaxCalculator _taxCalculator;
private readonly DiscountService _discountService;
public PricingService(TaxCalculator taxCalculator, DiscountService discountService) {
_taxCalculator = taxCalculator;
_discountService = discountService;
}
public decimal CalculateTotalPrice(SalesOrder order) {
decimal totalPrice = 0;
// Sum the price for each row in the order
foreach (var row in order.Rows) {
totalPrice += row.Quantity * row. Price;
}
// Apply discount if applicable
totalPrice -= _discountService.CalculateDiscount(order);
// Calculate and add tax
totalPrice += _taxCalculator.CalculateTax(totalPrice);
return totalPrice;
}
}
In PricingService , the CalculateTotalPrice method handles the logic of summing the prices of all rows in the sales order, applying any discounts, and then calculating and adding the tax. The tax calculation is delegated to a separate TaxCalculator service, and the discount calculation is delegated to DiscountService , each encapsulating specific parts of the pricing logic.
The TaxCalculator service is responsible for tax calculations. By isolating tax logic in its own service, we adhere to the SRP and ensure that each service has a clear and focused purpose:
public class TaxCalculator {
private readonly decimal _taxRate;
public TaxCalculator(decimal taxRate) {
_taxRate = taxRate;
}
public decimal CalculateTax(decimal amount) {
return amount * _taxRate;
}
}
TaxCalculator takes a tax rate as a dependency and uses it to calculate the tax on a given amount. This service can be easily modified or extended to accommodate different tax rates or complex tax rules without affecting PricingService .
DiscountService is responsible for applying discounts to the sales order. This service ensures that discount logic is encapsulated separately, making it easier to manage and modify. Here is the sample code for a simplified discount service:
public class DiscountService {
public decimal CalculateDiscount(SalesOrder order) {
if (order.Discount == null) {
return 0;
}
var result = //… do some calculations…
return result
}
}
DiscountService applies the appropriate discount to the order if one is available. This separation of discount logic allows PricingService to remain focused on its core responsibility of calculating the total price.
Application services
Application services sit above the domain layer, orchestrating the domain objects to fulfill a particular use case. They act as a bridge between the presentation layer (such as a web API or the user interface) and the domain layer, handling tasks such as transaction management, authentication, and authorization. Unlike domain services, application services can have side effects and interact with external systems.
Returning to our brewery ERP, imagine the process of creating a new sales order. This involves several steps: validating the order details, checking product availability, calculating the total price, and finally, saving the order to the database. These steps encompass various domain operations orchestrated by an application service, as shown in the following code:
public class SalesOrderService {
private readonly ISalesOrderRepository _salesOrderRepository;
private readonly PricingService _pricingService;
private readonly WarehouseService _warehouseService;
public SalesOrderService(ISalesOrderRepository salesOrderRepository, PricingService pricingService, WarehouseService warehouseService) {
_salesOrderRepository = salesOrderRepository;
_pricingService = pricingService;
_warehouseService = warehouseService;
}
public SalesOrder CreateSalesOrder(SalesOrderDto orderDto) {
// Validate order details
SalesOrder order = new SalesOrder(orderDto);
// Check product availability
_warehouseService.CheckAvailability(order);
// Calculate total price
decimal totalPrice = _pricingService.CalculateTotalPrice(order);
order.SetTotalPrice(totalPrice);
// Save order to the database
_salesOrderRepository.Save(order);
return order;
}
}
In the preceding example, SalesOrderService orchestrates the entire process of creating a sales order, utilizing domain services such as PricingService and WarehouseService , and managing persistence through SalesOrderRepository .
SalesOrderService starts by validating the order details and converting the DTO into a SalesOrder domain entity. It then checks the availability of the products in the order using WarehouseService . Next, it calculates the total price of the order, including discounts and taxes, by calling PricingService . Finally, it saves the completed order to the database using SalesOrderRepository .
Key differences between domain and application services
The primary difference between domain services and application services lies in their focus and scope. Domain services encapsulate domain-specific logic that spans multiple entities, while application services coordinate the use of domain objects to accomplish higher-level tasks.
When you need to encapsulate business logic that pertains to the domain but doesn’t naturally belong to a single entity, you should use domain services. This is especially useful for complex business rules or processes that involve multiple entities. On the other hand, application services should be used to manage use cases and workflows that involve multiple domain operations. They handle coordination tasks, transaction management, and interactions with external systems.
To summarize, the proper use of domain and application services ensures a clean separation of concerns, making your code base more maintainable and scalable. In our brewery ERP system, domain services such as PricingService , TaxCalculator , and DiscountService , along with application services such as SalesOrderService , work together to handle the complexities of sales order processing, each fulfilling their specific roles within the architecture. By leveraging these concepts, you can build systems that are both robust and adaptable to changing business requirements.
Modules
A module is essentially a way to group related concepts and functionalities within a software system, encapsulating them to reduce interdependencies and promote a clear structure. By organizing code into well-defined modules, you can better maintain, understand, and evolve your application. A module plays a pivotal role in managing the complexity of large systems.
Modules serve as the building blocks for a robust and scalable system architecture in DDD. Their primary purpose is to help you manage the inherent complexity of a large application by dividing it into smaller, more manageable pieces. This modular approach allows each module to focus on a specific aspect of the domain, promoting a high degree of cohesion within the module while minimizing coupling between different modules.
A module encapsulates a cluster of related domain concepts, which might include entities, value objects, aggregates, and services. This encapsulation helps you maintain a clear separation of concerns. Each module handles a specific aspect of the domain, making it easier to understand and manage. Moreover, well-defined interfaces and boundaries between modules simplify the communication between different parts of the system, reducing the risk of unintended side effects and making it easier to understand how different parts of the system interact.
Implementing a modular approach in your projects can offer numerous benefits. Improved maintainability is a significant advantage. By breaking down the system into smaller, self-contained modules, you can make changes to one module without affecting the others. This reduces the risk of introducing bugs and makes it easier to test and maintain the code. Enhanced scalability is another benefit, as modules can be developed, deployed, and scaled independently, allowing you to address performance and scalability concerns more effectively. With clearly defined modules, different teams can work on separate parts of the system concurrently without stepping on each other’s toes, facilitating collaboration. Furthermore, modules can be designed to mirror the structure of the business domain, ensuring that the software system evolves in tandem with the business requirements, which leads to better alignment with business goals.
Let’s consider our brewery ERP system that handles sales orders to illustrate the concept of modules in DDD. In this system, you might have several modules, each focusing on a different aspect of the brewery’s operations. For example, the Sales module is responsible for managing sales orders, customer interactions, and invoicing. It might include entities such as Order , Customer , and Invoice , along with services for processing orders and generating invoices. The Warehouse module manages the brewery’s inventory, tracking the availability of ingredients, finished products, and supplies. This module includes entities such as Ingredient , Product , and Stock , as well as services for updating inventory levels and generating stock reports. The Production module oversees the brewing process, including scheduling production runs, monitoring fermentation, and ensuring quality control. It might involve entities such as Batch , Recipe , and ProductionSchedule , with services for managing production workflows and tracking batch quality.
By organizing the brewery ERP system into these modules, you can ensure that each aspect of the brewery’s operations is handled independently, with clear boundaries between different areas of functionality.
Modules in refactoring complex systems
Modules are particularly useful during the refactoring process of a complex system. As systems grow and evolve, they often become tangled and difficult to manage. By refactoring the system into well-defined modules, you can achieve several key benefits. One such benefit is the isolation of changes. When you need to modify a specific part of the system, you can do so within the confines of a single module, reducing the risk of unintended side effects. This also improves understanding, as clear module boundaries make it easier to understand the system’s structure and behavior, facilitating more effective debugging and problem-solving. Additionally, the modular design promotes incremental improvements. You can refactor and improve one module at a time, gradually enhancing the overall system without requiring a complete rewrite.
For instance, if the brewery ERP system needs to accommodate new sales channels, you can modify the Sales module without disrupting the Inventory or Production modules. This modular approach ensures that changes are contained and the overall system remains stable and maintainable.
While modules help structure and isolate different parts of a complex system, they often need to communicate with each other to reflect meaningful changes. This is where events come into play, enabling decoupled interactions between modules and ensuring that important state changes are properly propagated throughout the system.
Domain and integration events
In the context of software development, events are notifications that signify that something significant has occurred within the system. An event represents a change of state or the occurrence of a meaningful action. For instance, in our ERP application, events could include a sales order being placed, a payment being processed, or a beer order being shipped. Events are crucial in decoupling various parts of an application, enabling them to communicate and react to changes without being tightly coupled to one another.
They represent something that has happened in the domain that is of significance to the business. Events are used to communicate changes in the state of the domain. They are immutable facts that capture the state change and are often used to decouple different parts of the system, allowing them to react to changes independently. The fact that they represent something that has happened explains why they are written in past tense.
A practical example is the SalesOrderCreated event, which could look something like this:
public sealed class SalesOrderCreated(SalesOrderId aggregateId, Guid commitId, SalesOrderNumber salesOrderNumber, OrderDate orderDate, CustomerId customerId, CustomerName customerName, IEnumerable<SalesOrderRow> rows) : DomainEvent(aggregateId, commitId)
{
public readonly SalesOrderId SalesOrderId = aggregateId;
public readonly SalesOrderNumber SalesOrderNumber = salesOrderNumber;
public readonly OrderDate OrderDate = orderDate;
public readonly CustomerId CustomerId = customerId;
public readonly CustomerName CustomerName = customerName;
public readonly IEnumerable<SalesOrderRow> Rows = rows;
}
The SalesOrderCreated event is a domain event that captures the creation of a sales order. It extends DomainEvent and contains essential information such as the order ID, customer details, order date, and the list of order items. By making this event immutable, we ensure that once it is published, its data remains unchanged, accurately representing a past occurrence in the business domain.
Later in this section, we will review the two kinds of events that exist in a DDD-oriented application:
- Domain events
- Integration events
But first, let’s review why they are a key concept in a modern application.
Importance of events in modern applications
Modern applications are becoming increasingly complex, often involving multiple services and components that must work together seamlessly. Events provide a way to manage this complexity by promoting a reactive and decoupled architecture. They enable horizontal scaling by allowing different services to process events independently. This scalability is essential for handling large volumes of data and user interactions. Furthermore, events contribute to the resilience of systems, allowing them to continue functioning even if some components are temporarily unavailable. Events can be stored and processed later, ensuring that no data or critical operation is lost. Additionally, events offer flexibility by facilitating the integration of new features and services. New components can subscribe to existing events without necessitating changes to the existing system, promoting a more adaptable architecture. Ultimately, events enable decoupling by separating the sender and receiver, resulting in more maintainable and modular systems.
Domain events
Let’s start with the first kind: domain events . These events, as you already know, are specific to the business domain and signify something that has happened within that domain. They are a critical concept in DDD, representing things that domain experts care about. For example, in our ERP application, events such as SalesOrderCreated , PaymentConfirmed , and BeerAvailabilityUpdated are domain events. These events reflect significant occurrences from a business perspective, capturing the essence of business operations and processes.
Domain events are characterized by their business relevance and . They represent occurrences that are significant from a business perspective and are of interest to domain experts. Domain events are immutable; once an event is created, it should not change. It captures a past occurrence and should remain a historical record. Additionally, domain events are self-descriptive. They should provide enough information for any interested party to understand what happened without requiring additional context or data.
An example is the BeerAvailabilityUpdated event, as shown in the following snippet:
public class BeerAvailabilityUpdated(BeerId aggregateId, Guid commitId, BeerName beerName, Quantity quantity) : DomainEvent(aggregateId, commitId)
{
public readonly BeerId BeerId = aggregateId;
public readonly BeerName BeerName = beerName;
public readonly Quantity Quantity = quantity;
}
The preceding code includes all the information on the availability of a specific beer as a reaction to the payment confirmation for a specific sale order.
Integration events
The second kind of event, and no less important, is integration events . They are used to communicate between different bounded contexts or external systems. While domain events are concerned with the business logic within a particular bounded context, integration events ensure that different parts of a distributed system stay in sync. They facilitate communication and coordination between different services or systems that need to work together to achieve a common goal.
Integration events are characterized by their role in cross-boundary communication. They are used to notify other systems or bounded contexts about changes, ensuring that the entire system remains consistent and up to date. Integration events help achieve loose coupling between services, making the system more modular and easier to maintain. This decoupling allows services to evolve independently without disrupting other parts of the system. Additionally, integration events often lead to eventual consistency, where different parts of the system eventually reach a consistent state after processing the events.
Soon enough, during your refactoring journey or development of a new feature, you will reach a point where a domain event in a certain bounded context appears to be identical to the integration event that you wish to send outside to let others synchronize with it. The temptation to use the domain one is high; we know that laziness can sometimes prevail over discipline, but try to refrain from doing it. That’s because sooner or later the ubiquitous language of your bounded context will inevitably change, and while there is a chance that you will probably change that domain event, it is not guaranteed that the integration event needs to change accordingly. In such a case, the two events would diverge; if you used the same event for both tasks, you can already imagine the impact on your entire application, not only on a single component.
Use cases in our brewery application
As mentioned in the previous chapters, our brewery application is composed of the following bounded contexts: Sales , Warehouse , Payment , and Shipping . Let’s explore how domain and integration events can be used within this system to facilitate communication and ensure seamless operations:
-
Sales context : In the
Salescontext, a significant domain event would beSalesOrderCreated. This event is triggered when a customer places an order. It is crucial for theSalescontext to track new orders and initiate the subsequent processes required to fulfill the order. -
Warehouse context : In the
Warehousecontext, a critical domain event would beBeerAvailabilityUpdated. This event is triggered when stock is reserved for an order. It is essential for managing inventory within theWarehousecontext, ensuring that the necessary items are available and reserved for the customer order. -
Payment context : In the
Paymentcontext, a key domain event would bePaymentProcessed. This event is triggered when a payment is successfully processed. It is important for thePaymentcontext to track the payment status and ensure that the order can proceed to the next stage. -
Shipping context : In the
Shippingcontext, a significant domain event would beShipmentCreated. This event is triggered when a shipment is created for an order. It is crucial for theShippingcontext to manage deliveries and ensure that the order is dispatched to the customer. -
Integration events across contexts : Integration events play a vital role in ensuring that different bounded contexts within the brewery application stay in sync and communicate effectively. When a
SalesOrderCreateddomain event is triggered in theSalescontext, it will also trigger an integration event (that could have the same name) that is published to other bounded contexts. TheWarehouse,Payment, andShippingcontexts subscribe to this event to initiate their respective processes. For example, theWarehousecontext allocates stock, triggering theBeerAvailabilityUpdateddomain event, which then triggers an integration event to notify theSalescontext about stock reservation.
These domain and integration events form a chain of reactions across the system, ensuring that each bounded context remains informed and can act accordingly. To better understand how these events propagate and influence different parts of the application, let’s examine the overall event flow and how information moves throughout the system.
Event flow and information flow
To illustrate a complete flow of events and information within our application, consider the diagram in Figure 4 .2 :
Figure 4 .2 – Diagram of a business flow with events
When a customer places an order in the Sales context, the system triggers the SalesOrderCreated domain event. This event is significant within the Sales context as it marks the initiation of the order fulfillment process. Concurrently, an integration event with the same name is published to the Warehouse , Payment , and Shipping contexts.
Upon receiving the SalesOrderCreated integration event, the Warehouse context allocates the necessary stock for the order. This allocation triggers the BeerAvailabilityUpdated domain event, which is crucial for managing inventory within the Warehouse context. The BeerAvailabilityUpdated event then becomes an integration event, notifying the Sales context about the successful reservation of stock for the order.
Meanwhile, the Payment context, upon receiving the SalesOrderCreated event, processes the customer’s payment. This action triggers the PaymentProcessed domain event, which is essential for tracking payment status within the Payment context. The PaymentProcessed event becomes an integration event, notifying the Sales and Shipping contexts about the successful payment, allowing them to proceed with their respective processes.
The Shipping context, after receiving both the SalesOrderCreated and PaymentProcessed events, creates a shipment for the order. This action triggers the ShipmentCreated domain event, which is significant for managing deliveries within the Shipping context. The ShipmentCreated event becomes an integration event, notifying the Sales context to update the customer about the shipment status and complete the order fulfillment process.
Sagas
As you will see in Chapter 12 , Orchestrating Complexity: Advanced Approaches to Business Processes , the flow we have just described is also called a choreography saga . In Chapter 12 , you will delve into the two main sagas that could be used to handle complex business flows.
Events, both domain and integration, play a pivotal role in modern complex applications by promoting decoupling, scalability, and maintainability. In our brewery application, domain events help manage business logic within bounded contexts, while integration events ensure seamless communication and synchronization across contexts. By understanding and leveraging these concepts, developers can build robust, scalable, and maintainable systems.
Summary
In this chapter, we delved deeply into the main tactical patterns of DDD. We started with entities, which are objects defined not by their attributes but by a thread of continuity and identity. These entities possess a distinct identity that runs through different states and transformations over time, making them critical in modeling real-world scenarios where identity persistence is crucial.
We moved on to value objects, which are defined entirely by their attributes. Value objects lack a distinct identity and are inherently immutable, offering a way to model concepts that can be described by their attributes alone, such as a quantity or a price. This immutability simplifies their use and ensures consistency across the system.
Aggregates were introduced as a key concept for maintaining consistency within the system. An aggregate is a cluster of entities and value objects that are treated as a single unit for data changes. The root entity of an aggregate guarantees the consistency of changes within the aggregate boundary, ensuring that all invariants are respected. This structure is vital for managing the complexity of business rules and data integrity.
Repositories were covered next. We explained their role in encapsulating the logic required to access data sources. By using repositories, you can abstract the infrastructure or technology-specific code, providing a clean separation between the domain model and data access layers. This separation enhances the maintainability and testability of the code.
We also explored the concept of services, distinguishing between domain services and application services. Domain services encapsulate domain logic that doesn’t naturally fit within entities or value objects, offering a way to express operations and processes within the domain model. In contrast, application services are responsible for orchestrating the application’s use cases, serving as a bridge between the user interface and the domain layer.
Modules were presented as a means to organize the domain model into cohesive units, enhancing the clarity and maintainability of the system. By grouping related concepts together, modules help manage complexity and facilitate a clearer understanding of the domain structure.
In the last section of the chapter, we delved into integration and domain events, underscoring their importance in modern application architectures. Integration events are pivotal for communication between bounded contexts or external systems, ensuring that changes in one part of the system are propagated and handled appropriately elsewhere. Domain events capture significant occurrences within the domain, making the system more responsive and robust by explicitly modeling the domain’s state changes and reactions.
Events are a key concept in modern complex applications because they enable a decoupled and reactive system design. By embracing an event-driven approach, you can achieve greater scalability and flexibility, handling real-time data and operations more effectively. Events allow different parts of the system to remain loosely coupled while still collaborating seamlessly, facilitating a more resilient and adaptive architecture.
This chapter marks the end of Part 1 , which reviewed the key concepts of DDD. In the next chapter, we will start to go deep into refactoring. You will learn about the principles of refactoring and how DDD can help in the process.