Introducing Refactoring Principles

In the previous chapter, we reviewed the tactical patterns of DDD and equipped you with a robust toolkit to model complex systems effectively. As you now understand, tactical patterns are crucial for aligning your software architecture with the core business domain. However, as systems evolve, even well-designed code bases can accumulate technical debt and become harder to maintain. This is where refactoring comes into play.

Starting with this chapter, you will embark on the journey of mastering refactoring principles, a critical skill set for any software developer working within the DDD paradigm. Refactoring is not merely about making your code cleaner—it’s about making it more aligned with the underlying business needs, more maintainable, and more resilient to future changes.

The chapter is structured around three core themes:

  • Understanding before acting
  • The pillars of safe change
  • Toward cleaner and more maintainable code

You will first learn the importance of thoroughly analyzing and comprehending the existing code base. This includes gaining insights into the current design, recognizing potential pitfalls, and identifying the right tools to facilitate the refactoring process. You will develop the skills to evaluate code with a critical eye, ensuring that every change is purposeful and aligned with the domain model.

Refactoring can be risky if not performed carefully. You will learn how to establish a safety net through the use of testing patterns, ensuring that every step of your refactoring journey is validated by reliable tests. This section will teach you how to create, maintain, and use these tests to detect unintended consequences early, minimizing risks and preserving the integrity of your application.

Finally, you will explore the application of design principles that guide effective incremental refactoring. By applying these principles, you will learn how to evolve your code base incrementally, making small, manageable changes that gradually lead to a cleaner, more maintainable, and more scalable system.

The complete code for this chapter can be found within the 01-monolith_legacy branch within the book’s GitHub repository here: https://github.com/PacktPublishing/Domain-driven-Refactoring/tree/01-monolith\_legacy.

Understanding before acting

If you take a look at the 01-monolith_legacy branch of our ERP example, you’ll notice that the code is somewhat messy. While the project names are clear, it’s difficult to identify any architectural pattern, such as Onion Architecture, Clean Architecture, or even Hexagonal Architecture.

Dig deeper into the code. If you open the program.cs file in the BrewUp.Rest project, you will see that every service and endpoint is registered in this file. This means that whenever you need to add, remove, or modify a service or endpoint, you have to update the program.cs file, the entry point of your application. This approach is far from ideal!

The SalesOrderService and WarehousesService files, located in the Services folder, serve as the façade of the underlying infrastructure. Placing these files directly in the BrewUp.Rest project creates a tight coupling with the underlying system. As a result, if you ever need to move one of these services out of the application as a standalone application, you will have to heavily modify the nt project once again and you will probably not be able to achieve that.

façade

A façade class offers a simplified interface to a complicated subsystem made up of many interconnected components. Although it simplifies access, a façade class may only offer partial functionality compared to interacting directly with the subsystem.

Challenges of Tight Coupling in Sales and Warehouse Services

Now, let’s focus on SalesOrderService in BrewUp.Domain\Services , which is invoked by SalesOrderService in BrewUp.Rest\Services . In this class’ constructor, as shown in the code that follows, you will notice the injection of two different instances of the IRepository interface: one for handling sales and the other for warehouse operations. This setup is necessary because when a request for a new order arrives, you need to check the beer availability before confirming the order. However, this approach creates a tight coupling between the Sales and Warehouses contexts. As you can see, any change within the warehouse context, beginning with the database schema, inevitably impacts the sales context. As a result, any modification to one service impacts the other, making it impossible to split these services into separate APIs due to their interdependence.

The following code demonstrates this:

public async Task CreateSalesOrderAsync(SalesOrderId salesOrderId, SalesOrderNumber salesOrderNumber, OrderDate orderDate, CustomerId customerId, CustomerName customerName, IEnumerable<SalesOrderRowJson> rows, CancellationToken cancellationToken)
{
    List<SalesOrderRowJson> beersAvailable = new();
    foreach (var row in rows)
    {
var availability = await warehouseRepository.GetByIdAsync<Shared.Entities.Availability>(row.BeerId.ToString(), cancellationToken);
        if (availability!=null)
            beersAvailable.Add(row);
    }
    var aggregate = SalesOrder.CreateSalesOrder(salesOrderId, salesOrderNumber, orderDate, customerId, customerName, beersAvailable);
await saleRepository.InsertAsync(aggregate.MapToSharedDto(), cancellationToken);
}

A major challenge with refactoring lies in the intricate web of dependencies between objects. When you modify one object, these dependencies often force you to make changes in others, creating a cascading effect. Therefore, before diving into refactoring, it’s crucial to identify the boundaries within different contexts. Understanding these boundaries equips you with the tools needed for effective refactoring.

Figure 5 .1 illustrates the ripple effect that any modification, regardless of the layer, has on the entire solution. This is one of the biggest challenges in maintaining and evolving a code base. Every time you need to introduce a new feature, you are forced to modify the entire solution. Given that no one fully understands the entire code base, there is a constant fear of introducing regressions or bugs. This fear often becomes a constraint, leading developers to resist making necessary changes.

Figure 5.1 – How changes impact all the monolith’s layers

Figure 5 .1 – How changes impact all the monolith’s layers

Attempting to transform a monolithic architecture into something different, such as a microservices architecture, in just one step will surely backfire on you. Gall’s law reminds us that complex systems evolve from simpler ones, emphasizing the importance of gradual transformation:

“A complex system that works is invariably found to have evolved from a simple system that worked. The inverse proposition also appears to be true: a complex system designed from scratch never works and cannot be made to work. You have to start over, beginning with a working simple system.”

The key to a successful evolution of your monolithic application relies on proceeding with small, incremental steps. This evolution starts by reorganizing your code base into modules applying architectural modularity. This is a stepping stone to architectural quantum, as you will see in the coming chapters.

However, what is a module? Modular architecture is based on the idea of breaking down a system into smaller, independent components, or modules, that can be developed, tested, and maintained separately. Within a module, objects can have dependencies on each other, but in this case, we are talking about cohesion rather than coupling.

Coupling versus cohesion

Cohesion refers to the degree of relation of the elements within a module, or component of a software system, that work together to achieve a common purpose. On the other hand, coupling refers to the degree of interdependence between different modules in a software system.

The primary goal of modularity is to enable teams to make changes to one part of the system without impacting others. This approach minimizes the risk of changes cascading through the system and causing unexpected issues.

After adopting a modular architecture, it’s crucial to establish clear communication methods between modules. Since your goal is to eliminate dependencies, implementing Consumer-Driven Contracts ( CDCs ) is essential. CDCs are agreements between service providers and consumers that specify how services should interact. These contracts are versioned and validated to ensure backward compatibility, allowing services to evolve independently without disrupting consumers. By explicitly defining and testing these interactions, CDCs support safe and incremental changes.

Incremental change involves making small, manageable adjustments to the system, rather than implementing large, sweeping modifications all at once. By breaking down changes into smaller increments, the scope of potential failure is significantly reduced, which makes it easier to isolate, test, and resolve issues before they escalate. This methodical approach allows for a more thorough understanding of the impact of each change, minimizing the risk of introducing new bugs or disruptions.

Moreover, incremental changes align well with continuous delivery and deployment practices. By integrating and deploying smaller updates frequently, teams can quickly roll out new features and fixes in a controlled manner. This reduces the time between development and production, allowing teams to respond swiftly to feedback and adapt to evolving requirements. The ability to make safe, incremental changes is crucial in maintaining system stability and ensuring that software can evolve over time without compromising quality or performance.

Before making any changes to your code base, it’s crucial to prepare the necessary tests to ensure your modifications don’t disrupt existing functionality. Automated testing involves creating and maintaining a suite of tests that cover various aspects of the application, such as unit, integration, End-to-End ( E2E ), and performance tests. Although it may not be feasible to cover all types of tests at this stage, prioritizing E2E tests is essential. The primary goal of refactoring is to improve the internal structure of the code without changing its external behavior. Automated testing acts as a safety net, helping to identify any regressions or issues that arise during the refactoring process, thereby ensuring that changes do not introduce new bugs or break existing features.

Establishing CI/CD and Observability in Refactoring

Another key aspect of the refactoring process is implementing Continuous Integration and Continuous Deployment ( CI/CD ). Legacy applications often lack these automated processes, so one of your goals should be to establish them. CI/CD pipelines automate the building, testing, and deployment of software. CI ensures that changes are frequently integrated, while CD automates the release of those changes to production. These practices shorten the time between making a change and seeing its impact in production, promoting rapid feedback and minimizing the risks associated with deploying updates.

Last but not least, once you have automated all the processes to build and deploy your application, you need to observe and monitor it. Observability involves the tools and processes to monitor the health and performance of the system in real time. The fundamental pillars of observability include logging, metrics, and tracing. Observability allows teams to detect and respond to issues quickly, minimizing the impact of any problems that arise from changes. It also provides insights into the behavior of the system, which can inform future changes.

These pillars work together to create a framework that supports the safe evolution of software systems. By adhering to these principles, teams can make changes with confidence, knowing that they have mechanisms in place to catch issues early and mitigate risks. This approach is essential in complex, distributed environments where changes are frequent, and the impact of failures can be significant.

During a refactor, developers often feel tempted to implement new patterns or frameworks they have learned, driven by both their ego (who hasn’t been there?) and the belief that patterns are the key to writing better code. However, this approach can be a double-edged sword. The following chart illustrates the idea that the more senior a developer becomes, the less complex their code tends to be.

Figure 5.2 – Code complexity versus experience

Figure 5 .2 – Code complexity versus experience

You should have noticed that at the beginning of the Experience axis, we wrote Super easy code , while at the end, it says Super simple code . That’s because writing easy code is in no way the same as writing simple code. The former just works but it is not well structured, maintainable, or readable while the latter tends to be all of them while maintaining simplicity.

As stated by Neal Ford in his book The Productive Programmer , “ Developers are drawn to complexity, like moths to a flame, often with the same outcome. ”

The pillars of safe change

It is now time to implement some solutions for the problems exposed in the previous paragraphs. As discussed, modularizing a monolithic system is an essential first step toward achieving a more flexible and maintainable architecture. Refactoring within this context requires a careful approach that aligns with the principles of modularity and incremental change. Our goal is to decouple tightly interwoven components so that they can evolve independently, reducing the risk of cascading changes and enhancing the system’s overall stability.

Exploring the solution structure

Let’s start by exploring how our project was initially developed by looking at the solution structure inside Visual Studio in Figure 5 .3 .

Figure 5.3 – The initial solution structure

Figure 5 .3 – The initial solution structure

As you can see, there is a little bit of DDD in it. As you should have already spotted, there is lots of coupling because everything is inside single folders of specific common projects. For example, BrewUp.DomainModel contains a folder named Services with both sales and warehouse services.

We know that we could do so much better with a bit of moving around, but before we dive deep into it and discover too late that we broke something, let’s try to apply the design and architectural principles introduced in previous chapters at the code level.

You can apply these principles by examining SalesService in BrewUp.Rest.Services . You can immediately see that SalesOrderService is tightly coupled with WarehouseService :

public sealed class SalesOrderService(
    [FromKeyedServices("sale")] IRepository saleRepository,
    [FromKeyedServices("warehouse")] IRepository warehouseRepository) : ISalesOrderService
{
    public async Task CreateSalesOrderAsync(SalesOrderId salesOrderId, SalesOrderNumber salesOrderNumber, OrderDate orderDate,
        CustomerId customerId, CustomerName customerName, IEnumerable<SalesOrderRowJson> rows, CancellationToken cancellationToken)
    {
        List<SalesOrderRowJson> beersAvailable = new();
        foreach (var row in rows)
        {
            var availability = await warehouseRepository.GetByIdAsync<Entities.Warehouses.Availability>(row.BeerId.ToString(), cancellationToken);
            if (availability != null)
                beersAvailable.Add(row);
        }
        var aggregate = SalesOrder.CreateSalesOrder(salesOrderId, salesOrderNumber, orderDate, customerId, customerName, beersAvailable);
        await saleRepository.InsertAsync(aggregate.MapToReadModel(), cancellationToken);
    }
}

Here, SalesOrderService is not only aware of the existence of WarehouseService but is also directly responsible for managing interactions with it. This tight coupling creates a situation where any changes to WarehouseService —even changes as minor as altering the method signature—could have ripple effects throughout SalesOrderService , thus violating the principles of modularity (remember the impact of changes as shown in Figure 5 .1 ).

These services are bound together, making it difficult to modify one without affecting the other. To move toward a modular architecture, we need to break this dependency, enabling each service to operate independently and making it easier to adapt the system incrementally.

However, before tackling the refactoring process head-on, it’s crucial to understand the role that tests play in ensuring a smooth and safe process. Refactoring, by its very nature, involves altering the internal structure of your code without changing its external behavior. However, this can be risky if not done with due care. This is where the concept of a safety net of tests comes into play.

Establishing comprehensive tests ensures that our changes do not inadvertently break existing functionality.

Understanding tests and their role in refactoring

At its core, a test is a piece of code that checks whether another piece of code (the system under test) behaves as expected. When you refactor an application, you inevitably change the code base, sometimes significantly. Without a robust set of tests, you have no reliable way to confirm that your changes haven’t introduced new bugs or altered the system’s behavior unintentionally.

Tests act as your first line of defense. They give you the confidence to make changes because you know that if something goes wrong, the tests will catch it. This is particularly important in a DDD context, where the alignment between the business domain and the code is critical. Any misalignment introduced during refactoring could have significant consequences on the overall design and functionality of the application.

Before reviewing the specific types of tests, it’s essential to grasp the variety available and how each serves a unique purpose in maintaining your application’s health.

In Figure 5 .4 , you can see the famous pyramid of tests , a concept that visualizes the optimal distribution of different types of tests in your code base.

Figure 5.4 – The pyramid of tests

Figure 5 .4 – The pyramid of tests

As you can see, the pyramid categorizes tests into three different layers: Unit tests, Integration tests, and E2E tests. Let’s discuss each of these and acceptance tests next:

  • Unit tests : Unit tests lie at the base of the pyramid and focus on individual units of code, typically functions or methods, verifying that they perform as expected in isolation. Unit tests are the fastest to run and are usually abundant in well-tested code bases. Their speed and granularity make them ideal for covering the smallest units of your application. They provide the foundation of your safety net and allow you to refactor with the confidence that the fundamental building blocks of your application will continue to function correctly.
  • Integration tests : In the middle layer, you have integration tests. They check how different modules or services work together. Unlike unit tests, they don’t isolate individual pieces of code but instead focus on the interactions between them. They are fewer in number and slower than unit tests but crucial for ensuring that the various parts of your system interact correctly. When refactoring, integration tests ensure that changes in one module don’t break its interactions with others. They provide a broader safety net, catching issues that unit tests might miss.
  • E2E tests : At the top layer lie E2E tests that simulate real user scenarios, testing the entire application from the user interface down to the database. These are the least numerous but the most comprehensive, testing the entire system as a user would interact with. While they are slower and more expensive to maintain, their ability to validate complete user flows makes them indispensable. When refactoring, E2E tests assure you that the application’s core functionalities remain intact.
  • Acceptance tests : There is also a fourth layer not represented in the original pyramid that tends to overlap with the E2E tests. That layer is made up of acceptance tests. These tests are often written from the perspective of the end user or the business. They validate that the system meets the specified requirements. As already stated, they overlap with E2E tests but are usually more focused on business outcomes than on technical correctness.

Applying the Testing Pyramid: A complete example

Each layer of the testing pyramid has its strengths and weaknesses. Unit tests, for example, are fast and easy to write, but they only cover individual components. If you refactor a significant portion of your code, unit tests alone might not be enough to guarantee that everything still works as intended.

Integration tests, while slower and more complex, give you confidence that different parts of your system interact correctly. However, they can be more challenging to maintain, especially if the integration points change during refactoring.

E2E tests provide the highest level of assurance but at the cost of speed and maintenance overhead. They are often brittle, meaning small changes in the code base can cause them to fail, even if the underlying functionality hasn’t been affected.

In conclusion, the simplicity and essence of the pyramid provide a couple of rules of thumb for choosing how many and which tests to write:

  • Write tests with different granularity
  • High-level tests should be significantly fewer in proportion to tests at lower levels

Let’s go back to the scenario explained in the Exploring the solution structure subsection at the beginning of this section. We could write unit tests that validate the interaction between SalesOrderService and WarehouseService , such as the following:

public class SalesOrderServiceTests
{
    [Fact]
    public void ProcessOrder_ShouldReserveInventory()
    {
        // Arrange
        var warehouseServiceMock = new Mock<IWarehouseService>();
        var salesOrderService = new SalesOrderService(warehouseServiceMock.Object);
        var order = new Order { BeerId = 1, Quantity = 10 };
        // Act
        salesOrderService.ProcessOrder(order);
        // Assert
        warehouseServiceMock.Verify(ws => ws.ReserveInventory(order.BeerId, order.Quantity), Times.Once);
    }
}

Writing many unit tests provides a foundation that allows you to refactor with confidence, knowing that any regression will be caught early.

Mock library

A mock library is a tool used in unit testing to simulate the behavior of real objects, allowing you to isolate and test specific parts of your code without relying on external systems. It helps ensure your tests are reliable, consistent, and fast by controlling the behavior of dependencies, making it easier to verify how your code interacts with other components. For this book, we choose to use Moq ( https://github.com/devlooped/moq ), a popular mock library for C# that makes it easy to create and configure mock objects for your tests.

Another set of tests you should consider writing before starting to apply any change to the code base are those on the presentation layer. To reference our pyramid, we should also write some integration tests. The following code should give you an idea:

[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);
}

In this test, we are making sure that the payload that arrives at our service is handled as it should be without bothering the internal working. What matters is that the result does not change. For this very reason, we did not call the specific method mapped to the /v1/sales/ endpoint as you would normally do with unit tests and a mock library. Instead, we emulated an HTTP call to be as abstract as possible.

By writing these tests in both the domain and application layers, we end up with the safety net we were talking about at the beginning of this section. We can finally move on to reorganizing our code base so that it relates to the bounded contexts already explained in Chapter 3 , Strategic Patterns .

Towards cleaner and more maintainable code

At the end of our journey, our goal is to refactor the application toward an architecture such as that in Figure 5 .5 .

Figure 5.5 – The end result of our refactoring process

Figure 5 .5 – The end result of our refactoring process

This is a well-organized code base. You should have already noticed that we used numbers in the solution folders’ names. We usually do this to clearly indicate the level of every layer of our application and, in our opinion, this follows the Onion Architecture pattern more closely. The solution folder we are referring to is just a logical folder that you can create to organize your projects inside IDEs such as Microsoft Visual Studio or JetBrains Rider. Obviously, you can easily achieve the same result with other frameworks and languages by using physical folders instead of logical ones.

A well-organized code base benefits all team members, including newcomers. It immediately clarifies the separation of concerns when opening the solution, making it easier to identify which component or module needs to be touched to introduce a new feature or solve a bug. Additionally, the presence of tests at every level reduces the fear of introducing regressions.

Also, an important thing you should have noticed right away is how the modules folder clearly represents the bounded contexts we defined and created in Chapter 3 .

Last but not least, Figure 5 .5 represents an event-driven approach paired with Command Query Responsibility Segregation ( CQRS ).

The term CQRS was coined by Greg Young in 2010. This architectural pattern is based on the principle of separating the responsibilities of commands (which modify state) and queries (which retrieve data) within a system. Young’s introduction of CQRS built upon Command Query Separation ( CQS ), which was originally defined by Bertrand Meyer in his 1988 book, Object-Oriented Software Construction .

In our specific case, the commands are found in BrewUp.Sales.Domain and BrewUp.Warehouses.Domain , while the queries part are handled by BrewUp.Sales.ReadModel and BrewUp.Warehouses.ReadModel .

CQRS is often used in conjunction with event sourcing to enhance system architecture by providing clear boundaries between read and write operations, thereby improving scalability and maintainability, hence the definition of CQRS+ES .

In Figure 5 .6 , you can see how a CQRS+ES system works.

Figure 5.6 – CQRS+ES diagram

Figure 5 .6 – CQRS+ES diagram

In Chapter 7 , Integrating Events with CQRS , we will start the refactoring process by implementing CQRS and then add events for communication between bounded contexts.

As with all things in life, to be able to solve or work on large complex problems, you must break them down into smaller ones. As far as our architecture is concerned, it is not advisable to refactor directly to CQRS+ES in one step, but instead, as reiterated multiple times throughout this book, take small steps.

To conclude our tour of the tools we need in our toolbox to be able to do what we described, we must review the last principles essential to successful refactoring. These design patterns play a pivotal role in ensuring that the system remains flexible, maintainable, and scalable.

Single responsibility principle

One of the foundational principles is the Single Responsibility Principle ( SRP ). The SRP states that a class or module should have only one reason to change, meaning it should be responsible for only one aspect of the system’s functionality. This is different from the common misconception that SRP means a class should simply ‘do one thing.’ Instead, it means that all the responsibilities of the class should align with a single, well-defined reason for change. When your code adheres to the SRP, it becomes easier to understand, test, and maintain because each component has a clear purpose. In the context of DDD, this principle ensures that your code reflects the distinct concepts of the domain, making the system more intuitive and aligned with business needs. It is essential for refactoring because it helps to break down complex, monolithic classes into smaller, more manageable pieces. Each class handles a specific aspect of the functionality, making the system easier to maintain and extend.

Using SalesOrderService and WarehouseService , as shown earlier in this chapter, we could refactor them as follows:

public class SalesOrderService
{
    private readonly IWarehouseService _warehouseService;
    public SalesOrderService(IWarehouseService warehouseService)
    {
        _warehouseService = warehouseService;
    }
    public void ProcessOrder(Order order)
    {
        if (_warehouseService.IsBeerAvailable(order.BeerId, order.Quantity))
        {
            // Process the order
        }
        else
        {
            // Handle out-of-stock scenario
        }
    }
}
public interface IWarehouseService
{
    bool IsBeerAvailable(int beerId, int quantity);
}
public class WarehouseService : IWarehouseService
{
    public bool IsBeerAvailable(int beerId, int quantity)
    {
        // Check availability in the warehouse
        return true; // or false
    }
}

Now, SalesOrderService is only responsible for processing orders, while WarehouseService only handles inventory checks, adhering to the SRP.

Open/closed principle

Another critical principle is the Open/Closed Principle ( OCP ), which posits that software entities should be open for extension but closed for modification. This means that the behavior of a class can be extended without modifying its source code. By adhering to the OCP during refactoring, you protect your system from the unintended consequences that often come with modifying established code. This approach not only preserves the integrity of your application but also facilitates the gradual introduction of new features.

Imagine we need to add a discount feature to SalesOrderService . Instead of modifying the existing code, we can extend the service using the OCP:

public class SalesOrderService
{
    private readonly IWarehouseService _warehouseService;
    private readonly IDiscountStrategy _discountStrategy;
    public SalesOrderService(IWarehouseService warehouseService, IDiscountStrategy discountStrategy)
    {
        _warehouseService = warehouseService;
        _discountStrategy = discountStrategy;
    }
    public void ProcessOrder(Order order)
    {
        if (_warehouseService.IsBeerAvailable(order.BeerId, order.Quantity))
        {
            decimal discount = _discountStrategy.CalculateDiscount(order);
            // Apply discount and process the order
        }
        else
        {
            // Handle out-of-stock scenario
        }
    }
}
public interface IDiscountStrategy
{
    decimal CalculateDiscount(Order order);
}
public class NoDiscountStrategy : IDiscountStrategy
{
    public decimal CalculateDiscount(Order order)
    {
        return 0;
    }
}
public class SeasonalDiscountStrategy : IDiscountStrategy
{
    public decimal CalculateDiscount(Order order)
    {
        // Implement seasonal discount logic
        return 10; // Placeholder discount value
    }
}

Here, we’ve introduced an IDiscountStrategy interface and implemented different discount strategies. We can now easily introduce new discount types without modifying the existing SalesOrderService logic.

Dependency inversion principle

The Dependency Inversion Principle ( DIP ) is another powerful tool in your refactoring arsenal. The DIP suggests that high-level modules should not depend on low-level modules; instead, both should depend on abstractions. This principle helps in decoupling your code, making it more modular and flexible. During refactoring, applying the DIP allows you to isolate changes to specific parts of the system, minimizing the ripple effect that modifications can have. This decoupling is particularly beneficial in large, complex systems where changes in one area should not unnecessarily impact others.

Consider a scenario where SalesOrderService directly depends on a concrete implementation of WarehouseService . This tight coupling makes it difficult to change or mock WarehouseService for testing.

Let’s apply the DIP to improve this:

public class SalesOrderService
{
    private readonly IWarehouseService _warehouseService;
    public SalesOrderService(IWarehouseService warehouseService)
    {
        _warehouseService = warehouseService;
    }
    public void ProcessOrder(Order order)
    {
        if (_warehouseService.IsBeerAvailable(order.BeerId, order.Quantity))
        {
            // Process the order
        }
        else
        {
            // Handle out-of-stock scenario
        }
    }
}
public interface IWarehouseService
{
    bool IsBeerAvailable(int beerId, int quantity);
}
public class WarehouseService : IWarehouseService
{
    public bool IsBeerAvailable(int beerId, int quantity)
    {
        // Check availability in the warehouse
        return true; // Placeholder logic
    }
}

The introduction of the IWarehouseService interface inside the constructor of SalesOrderService allows decoupling from the concrete implementation and allows us to create mock classes to fully unit test SalesOrderService .

Strategy pattern

The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. The pattern allows the algorithm to vary independently from the clients that use it.

This matters because this pattern is valuable when you have multiple ways to perform a certain task and want to make the system easily extendable with new strategies without modifying existing code.

Let’s expand our discount calculation logic using the Strategy pattern:

public interface IDiscountStrategy
{
    decimal CalculateDiscount(Order order);
}
public class NoDiscountStrategy : IDiscountStrategy
{
    public decimal CalculateDiscount(Order order)
    {
        return 0;
    }
}
public class PercentageDiscountStrategy : IDiscountStrategy
{
    private readonly decimal _percentage;
    public PercentageDiscountStrategy(decimal percentage)
    {
        _percentage = percentage;
    }
    public decimal CalculateDiscount(Order order)
    {
        return order.TotalAmount * _percentage;
    }
}
public class SalesOrderService
{
    private readonly IWarehouseService _warehouseService;
    private readonly IDiscountStrategy _discountStrategy;
    public SalesOrderService(IWarehouseService warehouseService, IDiscountStrategy discountStrategy)
    {
        _warehouseService = warehouseService;
        _discountStrategy = discountStrategy;
    }
    public void ProcessOrder(Order order)
    {
        if (_warehouseService.IsBeerAvailable(order.BeerId, order.Quantity))
        {
            decimal discount = _discountStrategy.CalculateDiscount(order);
            // Apply discount and process the order
        }
        else
        {
            // Handle out-of-stock scenario
        }
    }
}

In the preceding example, SalesOrderService can work with any discount strategy without needing to know the specifics of how discounts are calculated.

By embracing the principles and techniques we have discussed in this section, you will be able to systematically transform your code into a cleaner, more maintainable state. Each refactoring effort will contribute to a code base that not only better supports the current business requirements but is also more resilient and adaptable to future changes. Ultimately, this approach ensures that your system remains agile, responsive, and closely aligned with the evolving needs of the business domain.

In addition, the modular architecture we are working on will lead to the possibility of moving to a microservices architecture with less effort (you will read about it in Part 3 of this book).

Summary

This chapter has equipped you with a solid foundation in the principles and practices of refactoring within a DDD context. You learned that refactoring is not just about making code cleaner but also about aligning it more closely with the underlying business needs, enhancing its maintainability, and ensuring its resilience to future changes.

You learned about the importance of thoroughly analyzing your code base before taking any action, recognizing potential pitfalls, and selecting the appropriate tools for the job. The chapter highlighted the critical role of testing in the refactoring process, emphasizing how a robust suite of tests acts as a safety net, allowing you to make changes with confidence that your application’s integrity will be preserved.

Furthermore, you explored the application of key design principles, such as the SRP, OCP, DIP, and Strategy pattern. These principles will guide you in making incremental, manageable changes that lead to a cleaner, more maintainable, and more scalable system. The practical examples provided showed you how to tackle common challenges in refactoring, such as reducing tight coupling between services and transitioning toward a modular architecture.

As you move forward, the skills you’ve acquired—critical code analysis, comprehensive testing strategies, and the application of design principles—will empower you to refactor your code base effectively. This will ensure that your system remains agile, adaptable, and aligned with the evolving needs of your business domain, setting the stage for continued success in software development.

In the next chapter, we will start to refactor our monolithic code base into a well-organized modular monolith.

Get this book’s PDF version and more

Scan the QR code (or go to packtpub.com/unlock ). Search for this book by name, confirm the edition, and then follow the steps on the page.

A qr code on a white background
AI-generated content may be incorrect.

A white text on a black background
AI-generated content may be incorrect.

Note: Keep your invoice handy. Purchases made directly from Packt don’t require an invoice.