Transitioning from Chaos
In the previous chapters, we explored the challenges of navigating a tightly coupled monolithic architecture, using the tangled interactions between SalesOrderService and WarehouseService as a prime example. Now, it is time to bring structure to this chaos.
In this chapter, you will start to refactor your monolithic code base into a well-organized modular monolith using DDD principles. This transformation will not only improve maintainability and scalability but also align your software more closely with the core business domains it serves. You will learn how to identify core business domains, establish clear boundaries between components, and refactor tightly coupled services. By the end of this chapter, you’ll be equipped with practical techniques to create a more manageable and efficient architecture that reflects business needs while reducing complexity.
In this chapter, we will cover the following:
- Identifying core business domains in a monolithic application
- Decoupling tightly coupled services using clear domain boundaries
- Applying DDD principles to refactor a monolithic code base
- Implementing the facade and mediator patterns to simplify interactions and reduce dependencies
- Creating modular architecture with clearly defined interfaces and responsibilities
- Setting up automated tests and fitness functions to ensure architectural integrity during refactoring
This chapter will guide you through practical steps and real-world examples, preparing you to refactor complex systems and ensure your software evolves in a structured, maintainable way.
The complete code for this chapter can be found at the following branch in the book’s GitHub repository: https://github.com/PacktPublishing/Domain-driven-Refactoring/tree/02-monolith_with_cqrs.
Identifying core domains
When embarking on the refactoring of a monolithic application, it is common to encounter a code base that lacks clear boundaries around domain-specific areas. This is where DDD can help, but it is crucial to avoid common pitfalls, especially for first-time practitioners. One of the biggest mistakes is focusing too early on technical implementation details rather than on the business domain and its underlying logic. You learned about the complexity and problem space in Chapter 2 , Understanding Complexity: Problem and Solution Space .
At this stage, the key is to prioritize business strategies. Your goal should be to deeply understand the business and its various subdomains and let that inform your design. Consider our ERP system and the Customer entity as an example. If you attempt to use a single Customer entity across multiple subdomains such as Sales , Warehouses , and Purchases , you will create unnecessary interdependencies. Changes to the Customer entity in one context (such as Sales ) could unintentionally affect how the entity behaves in others, such as Warehouses or Purchases . This results in ambiguity and hinders the maintainability of the system. Instead, recognize that different subdomains might need their own version of Customer to reflect the specific needs of that area without creating a ripple effect across the system.
Imagine the sales team changes how orders are tracked, but because you are sharing the same Customer model across domains, it disrupts how the warehouse manages stock. Properly separating the domains lets you customize models for each part of the business without causing unintended ripple effects.
If you carefully observe the code in our ERP example, you will notice a significant issue of coupling within the SalesOrderService class. This class depends on two separate instances of the IRepository interface, meaning it has dependencies on both the Sales and Warehouses components. As a result, any change to the IRepository implementation for Warehouse will likely affect this class, even if the change is unrelated to Sales . This kind of tight coupling between components makes the system fragile and harder to maintain. It is a clear sign that the service is overly dependent on both contexts, creating unnecessary complexity.
In the next section, we will address this issue by focusing on decoupling these components. But the first crucial step is to establish clear boundaries between the Sales and Warehouse domains, allowing them to evolve independently without causing unintended side effects.
Understanding the business landscape
Identifying the right boundaries between components is a challenging task. It is not something that can be solved purely from a technical perspective. In these situations, you have to adopt the mindset of a software architect, which means understanding the broader business drivers and applying all the necessary trade-offs, not just focusing on the technical details. DDD offers valuable patterns to help identify these boundaries, but its true power lies in understanding the problem space. DDD emphasizes collaboration with customers and stakeholders, ensuring that your solutions are aligned with the business’s needs, not just its technical requirements.
Figure 6 .1 shows the boundaries of the contexts discovered in Chapter 3 , Strategic Patterns :
Figure 6 .1 – Well-defined bounded contexts
The idea is to replicate in your code base the contexts that you discovered in your exploration phase.
To avoid common pitfalls, it is essential to leverage DDD to focus on the most critical and valuable parts of the domain. Identify the areas that deliver the highest business value and ensure your modeling aligns with the company’s strategic objectives. Active collaboration with key business stakeholders is crucial for understanding their priorities and directing your efforts toward what matters most. By doing so, you ensure that your model accurately reflects the business’s needs and contributes to achieving its strategic goals.
Equally important is establishing close collaboration with domain experts from the very first stages of the design and development process. Regular engagement with them ensures that your understanding of the domain remains accurate and aligned with business needs. Involving domain experts in discussions, design sessions, and model reviews allows you to gather critical insights that shape the model. Techniques such as EventStorming and Domain Storytelling are particularly effective for facilitating collaborative modeling, ensuring that the model genuinely reflects the domain and its intricacies.
When you run an EventStorming session, start by gathering key stakeholders—sales, warehouse, and IT leaders. Lay out the core business events from end to end. Have each stakeholder explain how their domain works and map their processes on a whiteboard. This gives you insight into where dependencies and bottlenecks are lurking in your code.
To foster collaborative discussions within your team and gain a comprehensive understanding of the core domain driving your system, it can be helpful to ask yourself these questions:
- What are the primary functions of the systems? : This question clarifies the essential capabilities the system must deliver, ensuring alignment with the system’s core purpose.
- Which business processes are most crucial? : By identifying the most important business processes, you can prioritize system features that support the organization’s key objectives.
- How do different components interact to meet business requirements? : Understanding the interaction between system components ensures that they work together harmoniously to fulfill the business’s overall needs.
For instance, in our example, the key domains could include the following:
Sales : Responsible for managing customer orders, pricing, and promotions
Inventory : Focused on tracking stock levels and managing warehouse operations
Shipping : Handles the coordination of deliveries and logistics
By clearly defining these domains, you create a structure that mirrors the business’s core processes. This approach not only makes the code base more organized but also ensures that each part of the system aligns with the specific business area it supports.
Mapping the current code base
Once you have identified the core domains, the next step is to analyze your existing code base to find bottlenecks and areas where the architecture needs improvement. To do this effectively, follow these guidelines:
- Code analysis : Review classes, methods, and modules to evaluate how well they align with newly identified domains
- Dependency mapping : Use visualization tools to map out dependencies between components and identify areas of tight coupling
- Responsibility assessment : Assess whether modules adhere to the single responsibility principle or whether they handle multiple, unrelated concerns
The goal at this stage is to decouple the logical connections in your current code base and design a new architecture that better reflects the business processes and requirements. As a software architect, you must continuously balance business needs with technology choices. This is where the importance of establishing a shared language and model becomes clear, ensuring that everyone, from developers to stakeholders, understands and operates within the same context.
So far, you may discover that SalesOrderService not only handles order processing but also updates inventory levels directly, indicating a violation of domain boundaries.
Identifying bounded contexts
In DDD, bounded contexts define the boundaries within which a particular domain model is valid. They help manage complexity by isolating domain models that might have overlapping concepts but different implementations.
One of the essential tools that DDD offers is the concept of Ubiquitous Language , which helps in defining clear boundaries around domain areas. The first step is learning to actively listen to your stakeholders and paying attention to the language they use to describe their business processes. Terminology disparities between the business and technical teams often lead to misunderstanding, misaligned implementations, and a need for constant synchronization to ensure accurate translation of business logic into code.
Thanks to Ubiquitous Language, you can do the following:
Define contexts : Establish the bounded contexts within each domain. For example, the Sales domain might have contexts such as Order Management and Customer Relations .
Clarify terminology : Ensure that within each context, terms and concepts are used consistently. This is known as establishing a ubiquitous language.
By identifying bounded contexts, you can prevent the accidental mixing of domain logic and maintain clarity in your code base.
Another aspect that we want to reiterate is that the model you will come up with is not a copy of reality but an unavoidable simplification of it. This is because humans tend to try to simplify complex matters.
As we dive into code refactoring, it is important to first understand the value of having tests in place. Tests act like a safety net; they make sure that as we clean up and improve the structure of the code, we are not unknowingly breaking things.
However, for simplicity, we will not dive into the details of test creation right now. We will cover all the necessary tests at the end of this chapter. For now, let us stay focused on the main task (code refactoring), which is all about making the code more readable, maintainable, and efficient without changing its functionality.
Establishing clear interfaces
Now, we can start to decouple SalesOrderService and WarehouseService . To do so, we need to apply the concepts reviewed in Chapter 5 , Introducing Refactoring Principles and in the previous section, such as defining clear interfaces for the services so that we can encapsulate all their work to the outside world.
We want to restructure our project to reflect the domain boundaries. To do so, we need to do the following:
Physical separation : Organize code into separate directories or namespaces per domain
Logical separation : Ensure that classes and methods within a module pertain only to that domain
To achieve this, we can start by creating a solution folder named Modules with two subfolders named Sales and Warehouses in which we will create all the projects for the two bounded contexts.
In the Sales folder, we create a project named BrewUp.Sales.Domain , and the same in the Warehouses folder, this time named BrewUp.Warehouses.Domain . In these two projects, we move our aggregates and services as shown in Figure 6 .2 :
Figure 6 .2 – The new Sales project
The same changes must be applied to the Warehouses module as shown in Figure 6 .3 :
Figure 6 .3 – The new Warehouses project
We moved the classes and interfaces from the generic BrewUp.DomainModel to two specific projects to start to isolate sales and warehouses and, of course, we also updated their namespaces.
So far so good, but what about persistence? Shall we remain with the generic BrewUp.Infrastructure project? That’s right; of course, we cannot!
Every bounded context, as you already know, should be like a black box. It needs to have its own persistence. Let us start by creating the infrastructure projects for both sales and warehouses and move the relative repositories in them.
Basically, we want to move from the project of 01-monolith_legacy ( https://github.com/PacktPublishing/Domain-driven-Refactoring/tree/01-monolith_legacy)) in Figure 6 .4 :
Figure 6 .4 –The old infrastructure project
To the ones in Figure 6.5 :
Figure 6 .5 – The new infrastructure projects
This organization enhances readability and enforces the separation of concerns. Now that we have two well-defined groups of projects that map our bounded contexts, the next step will be to refactor the code base to create clear, well-defined interfaces.
We start by decoupling interdependencies. That is, identify tight couplings where one module depends heavily on the internal workings of another. In our case, SalesOrderService is calling methods deep within WarehouseService . It is time to introduce abstraction:
- Introduce interfaces : Define interfaces that expose only the necessary functionalities. Replace direct dependencies with interface implementations.
- Apply the dependency inversion principle : High-level modules should not be dependent on low-level modules; both should be dependent on abstraction.
This decoupling allows modules to evolve independently and reduces the risk of changes causing widespread issues.
To achieve this, we should create a facade for Sales and Warehouses so that the domain is not exposed outside, as shown for sales in Figure 6 .6 :
Figure 6 .6 – The facade project for sales
And we will do the same for the Warehouses module.
Facade pattern
The facade pattern is a structural design pattern that provides a streamlined interface to a complex subsystem. It acts as a front-facing interface masking more complex underlying or structural code. At its core, the facade pattern is about simplification and abstraction, offering a higher-level interface that makes the subsystem easier to use while abstracting its complexities behind a single interface. This pattern is particularly useful when you need to provide a simple interface to a complex subsystem. By implementing a facade, you can significantly reduce the complexity that clients have to deal with, shielding them from the intricacies of subsystem components. The facade pattern shares some similarities with other design patterns. For instance, while the adapter pattern converts one interface to another, the facade pattern defines a new interface. The mediator pattern is also similar, but its primary purpose is to abstract communication between objects.
Let us look at the SalesFacade.cs code:
public sealed class SalesFacade(ISalesDomainService salesDomainService,
ISalesQueryService salesQueryService) : ISalesFacade
{
public async Task<string> CreateOrderAsync(SalesOrderJson body, CancellationToken cancellationToken)
{
if (body.SalesOrderId.Equals(string.Empty))
body = body with { SalesOrderId = Guid.NewGuid().ToString() };
await salesDomainService.CreateSalesOrderAsync(new SalesOrderId(new Guid(body.SalesOrderId)),
new SalesOrderNumber(body.SalesOrderNumber), new OrderDate(body.OrderDate),
new CustomerId(body.CustomerId), new CustomerName(body.CustomerName),
body.Rows, cancellationToken);
return body.SalesOrderId;
}
public async Task<PagedResult<SalesOrderJson>> GetOrdersAsync(CancellationToken cancellationToken)
{
return await salesQueryService.GetSalesOrdersAsync(0, 30, cancellationToken);
}
}
In the preceding code, we expose CreateOrderAsync and GetOrderAsync for the other components of the systems to encapsulate the inner working and domain models.
The last thing that is missing is a helper to register the module’s services in the application.
We can easily do that by creating SalesHelper.cs with the following code:
public static class SalesHelper
{
public static IServiceCollection AddSales(this IServiceCollection services)
{
services.AddFluentValidationAutoValidation();
services.AddScoped<ISalesFacade, SalesFacade>();
services.AddScoped<ISalesDomainService, SalesDomainService>();
services.AddScoped<ISalesQueryService, SalesQueryService>();
services.AddScoped<IQueries<SalesOrder>, SalesOrderQueries>();
return services;
}
public static IServiceCollection AddSalesInfrastructure(this IServiceCollection services)
{
services.AddSalesMongoDb();
return services;
}
}
The preceding code is straightforward and as simple as it could be; it grants a cleaner organization of components and their infrastructure initialization. We created two methods that register the services of the module for the dependency injection that we will instantiate in the startup of our application.
Because we are talking about modules, in our startup project called BrewUp.Rest , which exposes the endpoints to interact with our application, we decided to write a little helper that has the responsibility of loading all the modules and keeping the code tidy.
Basically, we define a module class that has the responsibility of calling all the startup code of the model it refers to, such as the one defined in SalesHelper.cs .
These modules implement our interface named IModule :
public interface IModule
{
bool IsEnabled { get; }
int Order { get; }
IServiceCollection Register(WebApplicationBuilder builder);
WebApplication Configure(WebApplication app);
}
The two properties, in the preceding code, are there to control the call order between modules (sometimes it needs to be instantiated before others) and whether that module should be loaded or not.
The two methods are called by the ModuleExtensions class, which has the responsibility of discovering all the classes that implement the IModule interface and call Register and Configure :
public static class ModuleExtensions
{
private static readonly IList<IModule> RegisteredModules = new List<IModule>();
public static WebApplicationBuilder RegisterModules(this WebApplicationBuilder builder)
{
var modules = DiscoverModules()
.Where(m => m.IsEnabled)
.OrderBy(m => m.Order);
foreach (var module in modules)
{
module.Register(builder);
RegisteredModules.Add(module);
}
return builder;
}
public static WebApplication ConfigureModules(this WebApplication app)
{
foreach (var module in RegisteredModules)
module.Configure(app);
return app;
}
private static IEnumerable<IModule> DiscoverModules()
{
return typeof(IModule).Assembly
.GetTypes()
.Where(p => p.IsClass && p.IsAssignableTo(typeof(IModule)))
.Select(Activator.CreateInstance)
.Cast<IModule>();
}
}
All the magic happens in the DiscoverModules method whereby, using reflection, we search all the classes that implement the IModule interface and create their instances.
With this code, we can instantiate all the module classes that we need without worrying about any startup file or configuration to update.
As a result, we will end up with a program.cs file without any kind of clutter, as in the following:
using BrewUp.Rest.Modules;
var builder = WebApplication.CreateBuilder(args);
builder.RegisterModules();
var app = builder.Build();
app.ConfigureModules();
app.Run();
What we are implementing can already be called architectural quanta . Because we are no longer focusing only on the code within the domain, we are already maintaining the infrastructure part. Databases, service buses, and so on are fundamental elements of our bounded context and, therefore, our module because they represent the operational part of it.
Architectural quanta
This concept refers to the smallest cohesive and autonomous unit within a software architecture that encapsulates a set of related functionalities. Each quantum has well-defined boundaries, a clear responsibility, and can operate independently or with minimal dependencies on other quanta. This concept aligns with the design principles of modularity, encapsulation, and separation of concerns. In DDD, a quantum often maps to a bounded context where each quantum can evolve independently, offering scalability, resilience, and flexibility in large, distributed systems, such as microservices. Quanta are the building blocks of a system’s architecture, allowing for isolated changes and independent deployment. You can read more on the topic in the book Fundamentals of Software Architecture by Mark Richards and Neal Ford.
Now that everything is set up, we can start writing the glue that will hold all the components cohesively by using the mediator pattern.
Building the modular monolith
Since the modules are independent and decoupled from each other, we need to create something to orchestrate the calls between them. This is where the mediator pattern comes in.
The mediator pattern encourages the decoupling of components that need to work together by eliminating direct communication between them. Instead of interacting directly, these components communicate through a mediator that is responsible for coordinating their interactions. This approach reduces dependencies between components as they no longer need to know about each other and rely solely on the mediator. As a result, the system becomes more flexible and maintainable, with each component depending only on the mediator rather than being tightly coupled to several others. Figure 6 .7 shows a representation of the mediator pattern.
Figure 6 .7 – The mediator pattern
Before diving into the code, let’s take a quick look at how the mediator pattern differs from the facade pattern so as to understand when it is best to use one or the other.
Mediator versus facade
In a tightly coupled monolithic system, SalesOrderService needs to directly call methods in WarehouseService , leading to messy, fragile code. By applying the mediator pattern, you ensure that these services communicate through a centralized interface, reducing direct dependencies and making the code easier to maintain.
First, the facade and mediator patterns are both used to simplify and manage interactions between objects, but they serve distinct purposes and have different characteristics, especially when applied to DDD.
Purpose
From the purpose point of view, the facade pattern provides a simplified, unified interface to a set of subsystems or complex components. Its main goal is to reduce the complexity for clients by providing a higher-level abstraction. It does not control the communication between the subsystems; instead, it just makes the system easier to use by hiding complexity. The mediator pattern focuses on controlling and coordinating interactions between multiple objects or components. It centralizes the communication between components, so they do not communicate directly with each other but through the mediator. This leads to reduced coupling between components.
Applied to the DDD context, the facade could serve as a high-level interface that wraps multiple domain services, repositories, or even application services. It simplifies the way external clients interact with the domain without exposing its internals. The mediator, instead, can manage interactions between domain objects or between domain services. It orchestrates the flow of information between various entities, aggregates, or modules in a way that decouples them. This can be useful in complex domains where multiple aggregates need to collaborate to fulfill a business operation.
Interaction
Moving to the interaction between components, the facade could be seen as a one-way abstraction that simplifies the interaction for the client. The subsystems behind the facade are still independent, and the facade does not control or mediate communication between them. It is simply an entry point that hides the underlying complexity. The mediator, on the other hand, controls bidirectional communication between components. It ensures that components do not talk directly to each other, reducing dependencies between them. Instead, they interact with the mediator, which decides how to propagate actions and responses.
Decoupling
Lastly, the facade does not decouple the internal components or systems it represents. It is an entry point to a complex system that does not change how the subsystems interact with each other. The purpose is to decouple the client from the complexity of the underlying subsystems, not to decouple the subsystems from each other.
The mediator decouples the components it coordinates by making them communicate only through the mediator. This results in less direct dependency between components, making the system easier to modify, extend, or maintain.
In Table 6.1 , we summarize the main differences between the facade and mediator patterns.
| Aspect | Facade | Mediator |
|---|---|---|
| Purpose | Simplifies the interface for clients by hiding complexity | Centralizes and controls communication between components |
| Decoupling | Decouples the client from subsystems’ complexity | Decouples components by mediating their communication |
| Interaction | One-way abstraction; does not control the interaction between components | Bidirectional interaction; controls the communication flow |
| Usage in DDD | Used in the application layer to simplify client access to domain services or APIs | Used in the domain layer to orchestrate interactions between aggregates, domain objects, or modules |
Table 6.1 – A summary of differences between the facade and mediator patterns
Going back to our code, let us create a new solution folder named Mediator inside the modules folder. After that, we should start by defining an interface named IBrewUpMediator.cs as in the following:
public interface IBrewUpMediator
{
Task<string> CreateOrderAsync(SalesOrderJson body, CancellationToken cancellationToken);
}
The concrete implementation would be like the following:
public class BrewUpMediator(ISalesFacade salesFacade, IWarehousesFacade warehouseFacade) : IBrewUpMediator
{
public async Task<string> CreateOrderAsync(SalesOrderJson body, CancellationToken cancellationToken)
{
List<BeerAvailabilityJson> availabilities = new();
foreach (var row in body.Rows)
{
var availability = await warehouseFacade.GetAvailabilityAsync(row.BeerId, cancellationToken);
if (availability.TotalRecords > 0)
availabilities.Add(availability.Results.First());
}
// Prepare the list of rows that are available for sale
List<SalesOrderRowJson> rowsForSale = (from row in body.Rows
let beerAvailability = availabilities.Find(a => a.BeerId == row.BeerId.ToString())
where beerAvailability != null && beerAvailability.Availability.Available >= row.Quantity.Value
select row).ToList();
if (rowsForSale.Count == 0)
{
return "No beer available for sale";
}
body = body with { Rows = rowsForSale };
return await salesFacade.CreateOrderAsync(body, cancellationToken);
}
}
In this way, we expose the method for creating an order so that sales and warehouse remain isolated and decoupled.
However, for everything to work, we must add one last thing. We need to create a couple of resources for our API endpoints so that the external clients can call our mediator’s methods.
We can do that by creating MediatorEndpoints.cs in the BrewUp.Mediator project:
public static class MediatorEndpoints
{
public static WebApplication MapMediatorEndpoints(this WebApplication app)
{
var group = app.MapGroup("/v1/brewup/")
.WithTags("BrewUp");
group.MapPost("/", HandleCreateOrder)
.Produces(StatusCodes.Status400BadRequest)
.Produces(StatusCodes.Status201Created)
.WithName("OrderBeers");
return app;
}
public static async Task<IResult> HandleCreateOrder(
IBrewUpMediator mediator,
IValidator<SalesOrderJson> validator,
ValidationHandler validationHandler,
SalesOrderJson body,
CancellationToken cancellationToken)
{
await validationHandler.ValidateAsync(validator, body);
if (!validationHandler.IsValid)
return Results.BadRequest(validationHandler.Errors);
var orderId = await mediator.CreateOrderAsync(body, cancellationToken);
return Results.Created($"/v1/brewup/orders/{orderId}", orderId);
}
}
In this class, other than exposing the endpoints, we also validate the inbound payload. We will not cover in detail how we do this because it is out of the scope of this book, but just know that we used the FluentValidation library that leverages all the invariants in a fluent approach. You can find the complete implementation in 02-monolith_with_cqrs in this book’s GitHub repository ( https://github.com/PacktPublishing/Domain-driven-Refactoring/tree/02-monolith_with_cqrs).)
With everything in place, you should have a project like the one in Figure 6 .8 .
Figure 6 .8 – The complete Mediator project
As stated at the beginning of this chapter, we chose to focus first on the refactoring of the code and then move to the testing part, but keep in mind that before starting with refactoring, it is mandatory to create the safety net that guarantees that we are not altering any functionality during the process.
Testing and stabilizing
Before starting refactoring, it is essential to have established end-to-end ( E2E ) tests to ensure the stability of the code base and to prevent introducing regressions or bugs.
In Chapter 5 , within the Understanding tests and role in refactoring section, you can find a detailed explanation of the E2E tests. The purpose of these tests is to verify that when you invoke an endpoint, the response matches your expectations. As outlined in Chapter 5 , these tests play a crucial role in ensuring that refactoring does not introduce unintended side effects. You can see an example of this approach here:
[Fact]
public async Task Can_Create_SalesOrder()
{
DateTime now = DateTime.UtcNow;
SalesOrderJson body = new(Guid.NewGuid().ToString(),
$"{now.Year:0000}{now.Month:00}{now.Day:00}-{now.Hour:00}{now.Minute:00}",
Guid.NewGuid(), "Customer",
now, new List<SalesOrderRowJson>
{
new()
{
BeerId = Guid.NewGuid(),
BeerName = "BrewUp IPA",
Quantity = new(10, "Lt"),
Price = new(5, "EUR")
}
});
var stringJson = JsonSerializer.Serialize(body);
var httpContent = new StringContent(stringJson, Encoding.UTF8, "application/json");
var postResult = await integrationFixture.Client.PostAsync("/v1/sales", httpContent);
Assert.Equal(HttpStatusCode.Created, postResult.StatusCode);
}
This is the behavior that your system exhibits before starting the code refactoring, and you must ensure that remains the behavior after you complete your work.
However, as you make architectural decisions, such as choosing modularity, it is equally important to protect these decisions as your system evolves. To achieve this, you need to ensure that everyone on your team maintains architectural integrity and avoids creating unnecessary coupling or technical debt. Since your goal is to evolve incrementally, the next critical step is to establish tests at the architectural level. These tests will ensure that the design principles and structure you have implemented remain intact as the system grows and changes.
An evolutionary architecture thrives on guided incremental changes. In a physics analogy, software systems resemble complex systems that naturally drift toward disorder, much like physical systems tend toward entropy. Just as energy is needed to maintain order in a physical system, software systems also require continuous effort. Software architects must consistently invest time and resources to maintain the structural integrity of the system, as it will not stay organized on its own.
As an architect, it is your responsibility to provide tools that ensure this guidance, and to be truly effective, these tools need to be automated. In the book titled Building Evolutionary Architectures authored by Neal Ford, Rebecca Parsons, and Patrick Kua, the authors describe a family of techniques, called fitness functions , which are used to automate many aspects of architectural governance. Fitness functions are essential in helping you monitor and enforce architectural principles as the system evolves, ensuring the architecture stays aligned with its intended goals.
Fitness functions
Fitness functions describe how well an architecture aligns with its intended goals. In test-driven development, you write tests to verify that features meet desired outcomes. Similarly, in fitness function-driven development, you write tests to measure how closely the system adheres to architectural objectives. These tests help you verify that your architecture continues to meet its intended purpose as the system evolves.
Fortunately, there are libraries available to help you implement fitness functions directly in your code without effort. For Java developers, ArchUnit ( https://www.archunit.org/ ) offers a robust solution, while .NET developers can use NetArchTest ( https://github.com/BenMorris/NetArchTest ). These libraries allow you to define and enforce architectural rules, ensuring that your system remains modular and follows the intended design principles.
Here is an example from our ERP system, demonstrating how to ensure that the Sales module does not depend on any other modules. The following fitness function helps protect the module’s isolation and ensures that no unintended dependencies are introduced over time:
[Fact]
public void Should_SalesArchitecture_BeCompliant()
{
var types = Types.InAssembly(typeof(SalesFacade).Assembly);
var forbiddenAssemblies = new List<string>
{
"BrewUp.Warehouses.Domain",
"BrewUp.Warehouses.Infrastructures",
"BrewUp.Warehouses.ReadModel",
"BrewUp.Warehouses.SharedKernel"
};
var result = types
.ShouldNot()
.HaveDependencyOnAny(forbiddenAssemblies.ToArray())
.GetResult()
.IsSuccessful;
Assert.True(result);
}
This test demonstrates how to implement a fitness function using NetArchTest to ensure that the Sales module in our ERP system does not have any unintended dependencies on another module, such as the Warehouse module.
The preceding piece of code can be broken down as follows:
-
Types.InAssembly(typeof(SalesFacade).Assembly);selects all types within theSalesmodule’s assembly, which, in this case, is the assembly whereSalesFacadeis defined. -
forbiddenAssembliesis the list of assemblies that theSalesmodule should not depend upon, such asWarehouses.Domain,Warehouses.Infrastructure,Warehouses.ReadModel, andWarehouses.SharedKernel -
ShouldNot().HaveDependencyOnAny(forbiddenAssemblies.ToArray())asserts that the types in theSalesmodule should not have dependencies on any of the forbidden assemblies listed. -
GetResult().IsSuccessfullevaluates the result of the dependency check to determine whether the test passed or not. -
Assert.True(result)finally asserts that the result is true, meaning theSalesmodule is free from unwanted dependencies. If there are dependencies, the test fails, flagging a violation of the architecture.
Refactoring is not complete until the new structure is robust and reliable. Introducing a modular architecture ensures that each module within your code base operates independently. The system’s entry points, such as REST endpoints, should avoid direct dependencies on any module’s internal logic. Such dependencies increase complexity and maintenance overhead by necessitating adjustments to the REST layer when modifying modules. To ensure independence, a fitness function can test that the REST project, BrewUp.Rest , relies solely on each module’s facade. Here is an example of such a fitness function:
[Fact]
public void Should_BrewUpArchitecture_BeCompliant()
{
var types = Types.InAssembly(typeof(Program).Assembly);
var forbiddenAssemblies = new List<string>
{
"BrewUp.Sales.Domain",
"BrewUp.Sales.Infrastructures",
"BrewUp.Sales.ReadModel",
"BrewUp.Sales.SharedKernel",
"BrewUp.Warehouses.Domain",
"BrewUp.Warehouses.Infrastructures",
"BrewUp.Warehouses.ReadModel",
"BrewUp.Warehouses.SharedKernel"
};
var result = types
.ShouldNot()
.HaveDependencyOnAny(forbiddenAssemblies.ToArray())
.GetResult()
.IsSuccessful;
Assert.True(result);
}
As you can see, in the preceding example, forbiddenAssemblies is the list of the projects inside each module, and the test asserts that there are no direct dependencies with them.
Summary
In this chapter, you tackled the challenge of transforming a chaotic monolithic code base into a well-organized modular monolith using DDD principles. You learned how to identify core domains and establish clear boundaries between components such as Sales and Warehouse , addressing issues of tight coupling and improving maintainability.
You explored the process of mapping the current code base, identifying bounded contexts, and establishing clear interfaces. You were also introduced to the concept of architectural quanta and showed how to implement it in your project structure. You learned about the differences between the facade and mediator patterns, and how to apply them effectively in your architecture.
The chapter guided you through building a modular monolith, demonstrating how to create a mediator to orchestrate communication between decoupled modules. You saw practical examples of how to implement these patterns in code, including the creation of endpoints for your API.
And last but not least, you learned about the critical role of testing in the refactoring process. The chapter emphasized the importance of end-to-end tests as a safety net before refactoring, and introduced you to the concept of fitness functions. You saw how to use tools such as NetArchTest to create automated tests that enforce architectural principles and prevent unintended dependencies between modules.
You acquired valuable skills in refactoring complex systems, implementing modular architectures, and using automated tests to maintain architectural integrity. These skills will help you create more maintainable, scalable, and robust software systems as you continue to develop your expertise in software development and architecture.
In the next chapter, you will start to implement Command Query Responsibility Segregation ( CQRS ), at first, without events, and then you will implement them too. You will also learn how to start testing event-driven architecture.