Strategic Patterns

As you learned in previous chapters, the biggest challenge at the start of any project—whether it’s a greenfield project or a refactoring effort—is the language. By now, the importance of understanding the domain and defining a shared language to build knowledge should be evident. However, creating a ubiquitous language comes with hidden challenges, often stemming from human behavior.

Now that you know how to avoid these mistakes, you are ready to discover the patterns that domain-driven design gives us and learn how to use them during the refactoring of your system.

To do so, we’ll cover the following main topics in this chapter:

  • Defining terms clearly
  • Dividing the domain
  • Dealing with communication between bounded contexts

By the end of the chapter, you will know how to strategically divide a domain into subdomains, understand their roles in your domain, and determine the optimal communication patterns. This refactoring operation will result in a modular solution that is also scalable and maintainable.

Defining terms clearly will solve half of the problem

In his book, Evans makes clear the importance of using the ubiquitous language in conversation with domain experts, and with all team members. To ensure that the comprehension of the problem is clear and without ambiguity due to an incorrect translation from the domain language to the technical language, it is important that the language used in our code base is as close as possible to the domain model. That is because the product that we deploy in production uses the technical language, not the business language.

To achieve that, during the conversation between teammates, no one needs to translate terms from one language to another. Since the software does not cope with ambiguity, we should base the conversation on the domain model. We will explain the domain model concept better later in the What is a bounded context? section of this chapter.

Evans is uncompromising about this:

“ By using the model-based language pervasively and not being satisfied until it flows, we approach a model that is complete and comprehensible, made up of simple elements that combine to express complex ideas…

“…Domain experts should object to terms or structures that are awkward or inadequate to convey domain understanding; developers should watch for ambiguity or inconsistency that will trip up design”

The ubiquitous language is not just a vocabulary; it is a rigorous language between all teammates who aim to remove all ambiguity and create a base to identify the boundaries around the business problem they have to solve.

During refactoring, it’s important to understand the model underlying the software we are working on before starting to modify the code. Having a common model of the business that every teammate can understand is the key to obtaining a clear architecture for the solution. It helps us to clearly identify the boundaries around the business problem, and having a common language is the first step. Try to think about a customer model; it seems easy to create a model of our customer, just including all properties such as invoice data, personal data, delivery addresses, headquarters addresses, and so on. We would then have a complete model of our customer. Most of the software that you are working on probably has a model similar to this one, and this is the primary pain point when you have to modify the behavior of the program or implement a new feature.

If you have to implement a new feature, for example, in the logistics area of your application, you probably have to modify the customer model. So far, you have usually been forced to change the model even in the sales area and purchases area, at minimum. As you already know, changing code in many areas is one of the main fears for a developer since it’s impossible to know what will happen in the system when you modify many components in your code base. By now, you should have started to understand the importance of having a model aligned with your business problem. A model that is too large forces you to change it every time you need to modify your code. A model that is too small is not enough to describe the problem itself. How can you design the right model? When you were younger, you probably played the telephone game. It was hilarious to discover that the sentence at the end of the line was totally different from the one at the beginning of it. At each step, when a child whispered the sentence to the ear of the next one in the line, the sentence invariably changed, leading to hilarious results.

Figure 3.1 shows the telephone game pattern in a real business situation. A domain expert explains their problem to an analyst, who explains the same (are you sure?) problem to an architect, and so on until it reaches the development team. They create a solution that will be deployed. Can you see the problem? Any person involved in this pattern has their own interpretation of the problem, which is different from that of the previous person in the line.

Figure 3.1 – The telephone game in a business situation

Figure 3.1 – The telephone game in a business situation

While the outcome is hilarious while playing the game, it is not so funny in the business world. Each time businesspeople try to explain a problem to technical people, they use their own language. To businesspeople, their own language is unambiguous. Since they know the problem, and they talk about it every day with colleagues or customers, they assume that the same mutual understanding exists with others.

This led to the creation of a solid language to communicate needs and solutions between the two groups. The technical people also have their own language, which is totally different from the one of the business. So, when these people have to create a model to solve the business problem described by the businesspeople, they have to translate a language into another one. Every time you translate something, you could lose important information or, worse, you might need to use your own words to describe what you understood.

This process is repeated at every step, from the customer to the analyst to the developer. Remember what we said about complexity, bias, and so on in the previous chapter?

How can you avoid this mistake? The first and simplest solution could be to remove the line between business experts and developers and get these people to communicate directly. Unfortunately, they use different languages, and this type of communication is impossible.

Figure 3.2 explains this solution. Domain experts and the development team talk among themselves directly, without any mediator. In this case, the problem isn’t the loss of information, but the language. Each of them uses a different language and cannot understand what the other says.

Figure 3.2 – Letting business- and technical people talk directly

Figure 3.2 – Letting business- and technical people talk directly

Hopefully, you are now seeing the importance of a ubiquitous language within the team. It guarantees the absence of ambiguity inside the communication, and it is the first step to building a domain model that is really helpful for everyone.

Finally, you can see the solution to the problem in Figure 3.3 . Using a ubiquitous language, each member of the team understands the other, and together they can build a domain model that’s helpful for everyone.

Figure 3.3 – Common domain model

Figure 3.3 – Common domain model

Having a model aligned with the business simplifies the refactor because now you and your business experts can understand each other without the need for translations or interpreters, and every new request that arrives will be perfectly aligned with your model. In addition, if the new request involves changing the model, you can rest easy knowing that changing the model will not affect the other functionalities of the system.

However, why do you need to create many models, and not just one, for your whole business? If the goal is creating software that can evolve, you need to create many small models, each of which is isolated from the other one. This is what bounded contexts are responsible for.

What is a bounded context?

A bounded context is a fundamental pattern of domain-driven design. It is the focus of strategic patterns and a central concept when you deal with large models because it allows you to split a big problem into smaller problems or a large model into smaller models.

Having small models helps us solve business problems and maintain our code in the future. To identify the boundaries around this fine-grained model, you have to use the ubiquitous language discovered previously to identify the pivotal events that move the discussion around the business problem from one context to another.

In our journey to discover the patterns inside domain-driven design and its implementation, we will use an ERP to manage a brewery. In this example, as you will see, we will start with an EventStorming workshop. You will meet the domain event , a pattern that we will discuss in , Domain and Integration Events , of this book. For the moment, you need to know that there are special events, the pivotal events, that help us to identify these boundaries because they have some specific properties.

One of these events is SalesOrderCreated . It is an event that changes the flow of the process. For instance, after a sales order is created, you have to verify the plafond availability of your customer, the beer availability in the warehouse, and the shipping conditions in the logistic area. The rules of the game have changed! After this event, you probably need new policies to handle all those cases. These policies could be in a different model that could also be in different bounded contexts.

You have to keep in mind that the core of domain-driven design is about designing software based on a model, one that all the teammates can understand. When this model will not map the business flow anymore due to the increased complexity and the components involved in it, you are definitely moving outside of the model boundary. When you deal with the refactoring of an old project, it is important to identify these boundaries, because the first thing you have to do after discovering them is to remove the coupling between objects that belong to different bounded contexts. Removing these coupling enables you to modify part of the system without the fear of breaking others, and that is a fundamental step!

Another element that you can use to draw boundaries between contexts is human behaviors. Back to the example of the sales order created, the behavior of the people involved in the payment system will be different from the people involved in the logistics department because they will have different tasks to perform. You have to capture these differences and use them to identify the boundaries of your contexts.

Once you have split the whole domain into many different bounded contexts, you need to find how these contexts communicate with one another. Like in the real world, each part of the system contributes to the final success, and the only way to achieve this is collaboration .

Dividing the domain into meaningful boundaries

The most obvious advantage of having a ubiquitous language is the ability to easily identify the boundaries around a business problem and split the domain into many subdomains. A business domain is the main area of activity of a company. In the example we will use in this book, the business domain is brewery management . The service that our hypothetical company provides is the production and selling of the best beer in the world! Easy.

It is important to understand that the business domain is not a software application. The software provides the solution you create to help your customer manage their business. A business domain is generally big and complex. So, as you have already discovered, having just one model to describe the whole business is impossible, and it is probably the situation that you will find yourself in when approaching refactoring. You can see the problem of having a “one-size-fits-all” model. It is a constraint for every new request and creates a fear of changing anything in your code due to the strong coupling between the components of your legacy application.

As in the real world, a company achieves its business domain goals by splitting the business itself into multiple areas. Domain-driven design does the same by splitting the domain into multiple subdomains. A subdomain is a small part of the whole domain and focuses on a particular aspect of the business. It is an important strategic pattern within domain-driven design. Therefore, a single subdomain is not enough to guarantee the success of a company. It is a cog in a more complex system: the domain.

In a complex system, each gear is assembled so that the whole system can fulfill its task; not every gear is important in the same way. In the context of a wheel, if you break a spoke, you can continue pedaling and finish your ride. However, if you puncture the tire, you must stop your ride, repair the tire, and then finish your ride. Both the tire and spoke are part of the wheel, but the tire is more important than the spoke. Likewise, if the goal of your company is to produce the best beer, having a good warehouse system will be important to stock the beers before selling them, but less important than having a perfect production department. None of these departments on their own will make your brewery profitable; all of these, and probably others, are necessary to achieve the goal, but it is imperative to identify the responsibilities of each one.

To identify the boundaries around these subdomains, you have to use the ubiquitous language discovered in the exploration phase with the domain experts and stakeholders. Any inconsistency in the ubiquitous language is a warning that something should be investigated more. That is because we could be talking about the same things but with different names, or we could be looking at a totally different thing that might belong to a different bounded context. You need to learn how to force your business experts to stay inside the problem space because you know how important this is. You need to identify whether you are talking about the customer for a sale order, or the customer for a delivery. You are certainly talking about a customer in either case, but in two different ways. That means having two different models, and, in this case, two different subdomains. You already know that a subdomain is a smaller area of knowledge or activity within a larger domain. Now you have also discovered that, as in the case of a cog or wheel, some subdomains are more important than others and there are different types of them. Splitting the whole domain into many subdomains means that you can create a smaller model and talk with specific domain experts to go deeply into the modeling. During the first part of the refactor, distilling a domain is extremely important to start with a good strategic design. The refactoring process is intended to improve the design, structure, and implementation of the software, as well as its non-functional attributes, without changing the functionalities.

Your goal is to reduce accidental complexity and improve code readability without side effects. Remember that you cannot transform a big ball of mud into a microservices solution in one step. Always keep Gall’s law in mind:

“ 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. ”

Generally, refactoring involves implementing a set of standardized small-scale modifications where each change is a minor adjustment to the source code of a computer program. These adjustments typically maintain the software’s existing functionality or, at the very least, do not alter its adherence to functional specifications. The author of Refactoring To Patterns , Joshua Kerievsky , wrote the following:

“By continuously improving the design of code, we make it easier and easier to work with. This is in sharp contrast to what typically happens: little refactoring and a great deal of attention paid to expediently add new features. If you get into the hygienic habit of refactoring continuously, you’ll find that it is easier to extend and maintain code.”

Splitting the whole domain into many subdomains is the first step of this process and is called context mapping .

It’s important to clarify that dividing a domain into multiple subdomains doesn’t necessarily require creating multiple autonomous services. The implementation could take the form of a modular monolith or a microservices-based solution. What truly matters is ensuring that a bounded context remains self-contained and does not span across multiple services or modules.

Context mapping

Context mapping is a technique used to visualize and understand the relationships and interactions between bounded contexts within a system. It involves creating a map that highlights how contexts relate to each other, identifies integration points, and exposes potential issues. This map becomes a critical tool in managing the complexity of large systems.

Drawing this map is not an easy task, however, and you should follow a series of steps to execute in a loop until you and your team reach a consensus on the outcome.

As a first step, identify the bounded contexts within your system. Each context should have a clear boundary and a specific domain model. Once you have your boundaries, you can move on to the next step, which could seem daunting at first. It involves defining how these contexts interact with each other. Are they dependent on each other? Do they share data or services?

Once you overcome this task with a reasonable, understandable web of connections, you should try to highlight the points where contexts integrate or need to communicate.

Lastly, you should be able to draw a visual representation of the contexts and their relationships. At the end of this chapter, you will end up with a complete diagram that illustrates the flow of information and its dependencies, as shown in Figure 3.12 . However, before going straight to it, let’s break it up into smaller steps so as to fully understand context mapping.

Firstly, Figure 3.4 shows how we could draw the context map of our ERP using the bounded contexts of customer, sales, warehouse, and shipping.

Figure 3.4 – A portion of our brewery’s context map

Figure 3.4 – A portion of our brewery’s context map

Types of subdomains

In our list of tasks to achieve a good mapping, the first step is to define specific domain models. However, what does that mean?

It means that every bounded context fills a specific role in your architecture, and you have to determine the importance of each one. This involves identifying which bounded contexts represent your core business logic, which ones support that core, and which ones are more generic in nature. By doing this, you can prioritize your efforts and resources effectively.

To achieve this, you need to analyze each bounded context and categorize it into one of the various subdomain types. This categorization helps you understand the strategic significance of each part of your system. Subdomains represent specific areas within a domain. They correspond to individual bounded contexts with their own set of rules and logic.

In context mapping, there are several types of subdomains you can choose from based on their role in your system. These are as follows:

  • Core subdomain
  • Supporting subdomain
  • Generic subdomain

By identifying which type each of your bounded contexts falls into, you can make informed decisions about how to approach their development, integration, and maintenance. For instance, you would likely invest more resources and innovation into your core domain, while perhaps looking for off-the-shelf solutions for generic domains.

This process of identification and categorization is crucial as it forms the foundation of your context map, guiding your overall architectural strategy and helping to align your technical efforts with your business priorities. Also, it deeply impacts how you structure your teams and the members within each one. For example, the team working on the core domain will probably be composed of the more experienced developers at first and maybe, at a later point, you will move some of them to other teams to share knowledge.

Now that you understand context maps, let us see what exactly they are and what purposes they serve.

Core subdomain

The core subdomain is the heart of your business. It is where your company’s unique value proposition lies and where you have a competitive advantage. This is the most critical and complex part of your system, requiring the most attention and resources. For our ERP, the sales system is the core domain, as it is central to the business’ operations and success.

Supporting subdomain

Supporting subdomains, while important, are not the primary focus of the business. They complement and enable the core subdomain but don’t provide the main competitive advantage. These subdomains are necessary for the business to function smoothly but aren’t where the company differentiates itself. In our ERP example, a customer service module would be a supporting subdomain – it’s crucial for customer satisfaction but not the main business driver.

Generic subdomain

Generic subdomains are common across many businesses and aren’t specific to your particular enterprise. These are often areas where reinventing the wheel isn’t necessary, and you can leverage existing solutions or outsource them. The invoice system is a good example of a generic subdomain – it is essential for monitoring revenue, but it’s not where a brewery would focus its innovative efforts.

Figure 3.5 shows a context map with the definition of every subdomain.

Figure 3.5 – Types of subdomains

Figure 3.5 – Types of subdomains

Understanding these different types of domains is crucial for effective context mapping and overall system design. It helps in prioritizing development efforts, allocating resources efficiently, and making strategic decisions about system integration and evolution. By recognizing which parts of your system fall into which subdomain categories, you can focus your innovative efforts where they matter most while finding efficient solutions for less critical areas.

Subdomains change over time

What we designed in this chapter is the first context map based on the knowledge acquired during the conversations with the brewery’s business experts. It tries to satisfy the business’ actual needs. Over time, the knowledge of the domain will improve, and the business flows will change with or without requests from the business experts. So, our bounded contexts or their importance in the domain could change accordingly. Last but not least, if you worked with your teams’ rotations, every member should be capable of taking on almost any subdomains.

Dealing with communication between bounded contexts

Now that you have a solid understanding of the importance of well-defined boundaries, we can move on to the last aspect of bounded contexts: communication. To build a cohesive system, these bounded contexts must interact effectively. That is why proper communication between bounded contexts is crucial. Strategic design offers some patterns to help you identify the best solutions based on our context of operation. Your goal here is to have a clear picture of how different parts of the system interact and relate with each other.

Importance of correct communication

Effective communication between bounded contexts ensures that the system functions as a unified whole. When bounded contexts fail to communicate correctly, inconsistencies and integration issues arise, leading to a fragmented system. Proper communication mechanisms help in the following ways:

  • Maintaining consistency : Ensuring that data and behavior are consistent across the system
  • Enhancing flexibility : Allowing bounded contexts to evolve independently without breaking the system
  • Reducing coupling : Minimizing dependencies between different parts of the system, making it easier to manage and refactor
  • Improving clarity : Providing clear interaction patterns, helping in understanding and maintaining the system

Communication patterns

These strategic patterns are high-level design strategies used to address and manage the relationships between bounded contexts. They provide a blueprint for handling integration, collaboration, and governance across contexts. Some of the most relevant include the following:

  • Shared kernel
  • Customer-supplier
  • Conformist
  • Anticorruption Layer (ACL)
  • Open Host Service (OHS)
  • Published language
  • Separate ways

Shared kernel

In the shared kernel pattern, two or more bounded contexts share a portion of the same domain model. This shared part is managed collaboratively by the teams responsible for each context. This pattern is useful when contexts have strong interdependency and require a common understanding of specific aspects of the model.

Using our ERP as an example, consider the warehouse and sales contexts that share common details about the beer and stock levels. This shared kernel ensures that both contexts have a consistent understanding of product data, reducing the risk of discrepancies. The warehouse context manages stock levels, beer details, and warehouse locations, while the sales context handles customer orders, order processing, and fulfillment.

The shared kernel in this scenario includes details about the beer such as SKU, description, and price, which are critical for both contexts to function correctly.

Figure 3.6 – Shared kernel example

Figure 3.6 – Shared kernel example

Customer-supplier

The customer-supplier pattern establishes a clear upstream-downstream relationship between contexts. The upstream context provides services or data, while the downstream context depends on those services. The supplier (upstream) must ensure that the customer (downstream) can rely on its services, fostering a collaborative relationship.

For instance, the customer context (supplier) provides customer information to the sales context (customer). The sales context depends on accurate customer data to manage orders effectively. The sales context manages orders and payment processing, while the customer context handles plafonds and special categorization. The customer context must ensure that customer information is accurate and available in a timely manner for the sales context to function correctly.

Figure 3.7 – Customer-supplier example

Figure 3.7 – Customer-supplier example

Conformist

In the conformist pattern, the downstream context (conformist) adopts the model and communication protocols of the upstream context without influencing it. This pattern is used when the downstream context has little control over the upstream context and must conform to its way of working.

For example, a third-party payment processing service dictates the data format and interaction protocols, and the internal payments context must conform to these requirements. The payment processing service (external) provides payment gateways, transaction processing, and fraud detection, while the internal payment context manages internal payment flows, user payment data, and transaction records. The internal payment context must adapt to the protocols and data formats specified by the external payment processing service to ensure seamless integration.

Figure 3.8 – Conformist example

Figure 3.8 – Conformist example

ACL

The ACL pattern introduces a layer that translates and adapts between the models of two bounded contexts. This layer prevents the downstream context from being corrupted by the upstream context’s model, allowing each context to maintain its integrity.

In our ERP platform, the sales context might use an ACL to translate data from the legacy CRM system into its own model. This ensures that the sales context is not polluted by the outdated CRM model. The legacy CRM system manages customer relationships, historical data, and sales interactions, while the sales context handles current sales processes, customer interactions, and order management. The ACL translates CRM data into the format and structure required by the sales context, ensuring data integrity and consistency.

Figure 3.9 – ACL example

Figure 3.9 – ACL example

OHS

The OHS pattern involves exposing a bounded context’s capabilities through a well-defined service interface, making it an open host for other contexts to interact with. This pattern promotes loose coupling and clear contracts between contexts.

For instance, the shipping context might provide an OHS that allows other contexts, such as sales and warehouse, to request shipping services through a standard API. The shipping context manages shipping rates, carriers, and tracking information. The sales context requests shipping services for order fulfillment, and the warehouse context requests shipping information for stock transfers and replenishments. The shipping context exposes its services via an API, enabling other contexts to interact with it without tight coupling.

Figure 3.10 – OHS example

Figure 3.10 – OHS example

Published language

The published language pattern entails defining a shared language (a set of common terms and data structures) that multiple bounded contexts use for communication. This shared language reduces misunderstandings and integration complexity.

In a microservices architecture, a common event schema might be used for inter-service communication. This ensures that all services understand the event data consistently. For example, the sales context publishes order events when new orders are placed. The warehouse context consumes order events to update stock levels, and the invoice context consumes order events to generate invoices. The published language defines a common schema for order events, ensuring that all services can interpret the data correctly.

Figure 3.11 – Published language example

Figure 3.11 – Published language example

Separate ways

The separate ways pattern addresses the complexity that arises when two distinct parts of a system need to evolve independently. This pattern involves identifying bounded contexts within the domain that have minimal interaction and can be developed and maintained separately. By explicitly separating these contexts, teams can focus on the specific needs and rules of each domain area without being hindered by the intricacies of the others. This separation reduces coupling and allows for more agile and responsive development cycles, enabling each context to evolve at its own pace and in its own direction.

Final context map

In Figure 3.12 , you can see the complete context map of our ERP, describing the communication patterns between each bounded context. You can start with a pattern, such as conformist , and then change to OHS because you need to maintain a high level of separation between bounded contexts. When you need to communicate with external systems, you can choose to be conformist with them or to use an ACL to maintain your language inside your domain model. You are not forced to use just one of them; you have to use the right tool in the right place.

Figure 3.12 – Complete context map

Figure 3.12 – Complete context map

Refactoring complex systems with domain-driven design principles requires careful consideration of how bounded contexts communicate. Proper communication ensures consistency, flexibility, and clarity, enabling the system to function cohesively. By leveraging strategic patterns such as shared kernel, customer-supplier, conformist, ACL, OHS, and published language, teams can manage the relationships and interactions between bounded contexts effectively.

Summary

In this chapter, you delved deep into the strategic patterns of domain-driven design, discovering how vital it is to establish a ubiquitous language to eliminate ambiguity and ensure clear communication among all team members.

You learned that aligning the language used in your code with the domain models helps create a clear and comprehensible architecture, simplifying modifications and reducing errors. You learned how splitting large models into smaller, manageable bounded contexts is crucial for maintaining a system that can evolve without fear of unintended consequences. This approach allows you to isolate different business areas, making it easier to modify parts of your system without disrupting others. Finally, you were also introduced to several strategic patterns that help manage the relationships and interactions between these contexts. These include the shared kernel, customer-supplier, conformist, ACL, PHS, and published language patterns.

Each of these patterns offers a blueprint for maintaining consistency, flexibility, and clarity across the system, ensuring it functions as a cohesive whole. Understanding these patterns equips you to identify the boundaries within your domain and effectively manage the complexity of large systems.

In the next chapter, you will delve into tactical patterns, which will provide you with practical tools and techniques to implement the concepts you’ve learned so far.

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.