Microservices: Domain-Driven-Design (DDD)

·

10 min read

We will talk about DDD, what is it and it's trade-offs and when we should use it.

In short, DDD provides some strategic and tactical patterns that help you to implement your domain logic in a way that easier to understand develop and maintain.


What is DDD?

Domain Driven Design (DDD) is a software development approach for designing complex businesses. it's about Tacking the complexity in the Heart of Software.

DDD can be explained as a programming practice which focuses on the domain. DDD provides a set of patterns, terms, and good practices to build software from complex domains. It helps the developers manage the complexity they face when they design a solution.

DDD offers solutions to common problem when building enterprise software , It is especially useful to build systems that have a complex business domain. The main idea is to separate the business model from the infrastructure.

Before using this approach, ask yourself, is it necessary to use it? Does my application just need CRUD operations? So for that, do I need to use DDD? Each approach and design have its trade-offs, so try to use it with an open eye.

image.png

When can we use DDD approach?

Should you use DDD? If you’re developing a large system that has complexity at the heart, then yes, I recommend looking at some of the strategic (and tactical) patterns from Domain Driven Design. If you’re defining boundaries around capabilities and language (bounded context), guess what? You’re already doing Domain Driven Design!

good to read: thedomaindrivendesign.io/why-use-domain-dri..

image.png

Why DDD?

As one’s codebases grow, it is inevitable that their complexity will increase. As this happens, it tends to get more difficult to keep code organized and structured as originally intended In the traditional Model-View-Controller (MVC) architecture, the “M” layer would hold all the business logic, but would not provide clear rules on how to maintain proper responsibility boundaries. Several patterns came up to mitigate this problem, but still there was always risk of logic and responsibility leakage between components, making maintainability and stability trickier as the model evolved. On the other hand, communication with business experts, requirements gathering, and consensus between technical and non-technical teams to properly design and implement a system that solves a business problem is a constant iterative process where things can easily get misinterpreted, and ultimately derail the project from its original goals.

Naming things, for example, has always been one of the most difficult challenges Software Developers face. We should be clear enough for other developers to understand our intentions in the code, while using appropriate naming choices that can facilitate a conversation with business stakeholders.

Domain-Driven Design (DDD) attempts to solve these challenges, by reconciling the technical and non-technical forces that collide in a software project, and proposing a set of practices and patterns that facilitate building a successful system.

DDD is not architecture

Initially the DDD is adopted as a set of patterns and good practices of software development. If you associate that a project uses DDD because of Entities, Services, Repositories, etc. And in rare situations it also uses Value Objects, Aggregates, Events, Modules and Factories.

Doing DDD is about understanding your domain and modeling your domain, finding the boundaries, there is value in the patterns of aggregates which form, there's value in tactical patterns but that shouldn't the focus when you're doing DDD, just because you have repositories and entities and value objects, that means that you have those, that doesn't necessarily that you're doing DDD. Focusing on the domain and boundaries is the most important thing about doing DDD. DON'T JUST USE TACTICAL PATTERNS

If you’re writing a relatively small application without much complexity, don’t get caught up with trying to apply the tactical patterns.

Strategic Design and Tactical Design

What is Strategic Design ?

Strategic Design: Splitting your design so as to not lose your mind

As the implementation evolves through many iterations, and the system’s complexity grows progressively, it can be daunting to maintain control over it. Therefore, a rigorous strategy to comprehend and control large systems is fundamental. Breaking down the model into Bounded Contexts that interact with each other — which themselves have their own unified model both in concept and in code — is an effective way to avoid complexity pitfalls.

it is a pillar of the DDD whose main goal is to define Bounded contexts, Ubiquitous Language and Context Maps along with the entire project team.

In the Strategic Design we explore the problem space we want to find all the various Domain and subdomains that the system has.

Bounded Context

A Bounded Context is a conceptual boundary around parts of the application and/or the project in terms of business domain, teams, and code. It groups related components and concepts and avoids ambiguity as some of these could have similar meanings without a clear context.

image.png

Ubiquitous Language

It defines a common set of vocabulary to express the model. DDD focuses on building a simple, business-oriented language, skipping technical names or concepts. In this way, the main goal of ubiquitous language is to avoid misunderstandings and bad assumptions, a language that is well understood by everybody.

It is purely a set of terms (verbs, nouns, expressions, etc.) shared by all parties involved in the project, such as programmers, architects, business experts, and employees in the organization we are working for, among others.

In the end, this set of terms will be easily understood by domain experts and technical people alike. It should be used in all ways of communication and interaction.

It must not be ambiguous and unclear, at least in a specific context, such as a bounded context.

Ultimately this Ubiquitous Language will be embedded in the code.

Context Map

The context map is simply a diagram, which explicitly represents a map of all the context boundaries and the way they communicate with each other.

image.png

What is Tactical Design ?

The Tactical Design, is a set of technical resources used in the construction of your Domain Model, these resources must be applied to work in a single Bounded Context.

Also called tactical modeling, it is a pillar of DDD related to “Building Blocks“, which are Entities, Services, Repositories, Value Objects, Aggregates, Events, Modules, Factories, etc.

**Repositories ** Repositories are mainly used to deal with storage, they abstract concerns about data storage. They are responsible for persisting Aggregates.

Factories

Factories are used to provide an abstraction in the construction of an Object, and can return an Aggregate root, an Entity, or an Value Object. Factories are an alternative for building objects that have complexity in building via the constructor method.

You need to understand that not all of these concepts need to be applied to your Domain Model, you need to do an analysis so that it does not add unnecessary complexity to your project.


Use cases in microservices:

In each microservice than implementing the business logic, you will apply DDD principles. It provides strategic and tactical patterns that help you to implement your domain logic in a way that's easier to understand, develop and maintain.

Domain model = Conceptual model of the domain that defines the behavior and data of a system.

If you have already read my Hexagonal article, you should have caught the similarity, both Hexagonal architecture and DDD puts the domain logic in center of the software and makes it independent of the outside world.

Separating domain logic and infrastructure makes the software easier to design, develop, test, build and maintain over time. It will keep the domain logic stable and helps you to change the infrastructure components and adopt to new technologies easily.

There are two sides of DDD: 1- Strategic DDD: focuses on boundaries in a domain model. Single Bounded context per each domain

  • What is a Domain? Operational area of your application.

  • Bounded Context: Central pattern in DDD. Boundary within a Domain.

    image.png

    2- Tactical DDD: focuses on the implementation details of the domain logic.

  • Entities: are the core domain objects they have the critical business logic and entity must have a unique ID, Entity objects are immutable objects as it will run some business logic and update the properties based on the calculations

image.png

3- Aggregates: which is a group of Entity objects that are logicly related which always need to be in consistent state. one or more domain that always need to be consistent as a whole are called an aggregate For example, you may have an order process aggregate that includes Order, Order Item, Product Entities.

image.png

The important thing with an aggregate is that it should be retrieved and stored as a whole consistent state

4- Aggregate Root (AR): The entity that is the root of the aggregate and has other entities and value objects inside it's class is called the aggregate root.

image.png

5- Value Object: are used to bring context to the value. Immutable objects without identity. Only value matters. For example to keep a price of and order. Also you can have business operations in Value Object with methods and allow validations in constructor.

image.png

one important feature of Value Objects is that it is immutable. It mean when you created once you cannot change its value, if you want to change the value you should simply create a new Value Object with the updated value.

If you take two entities they are considered equal if they have the same ID event if the values are completely different, and two value objects are considered the same if the values of the properties are equal.

6-Domain Service Business logic that cannot fit in the aggregate . Used when multiple aggregate required in business logic Can interact with other Domain service

image.png

Domain Service is still in the core of the domain logic, so it cannot be reached from outside. And to communicate with outside from the domain logic, we are coming to Application Services

7- Application Services: These are services that exposes the required domain methods to the outside. Allows the isolated domain to communicate with outside. transaction, security, looking up proper aggregates and saving state changes of the domain to the database. Does not contain any business logic. It is the application services responsibility to get the data and pass into the domain service or entities. Regarding domain events and domain event listeners, can be thought of as special kind of application service, the only diffeence is that Domain Event Listeners are not triggers by the end users but by the Domain Event

image.png

The benefits of Domain-Driven Design

For complex applications, adopting a domain-driven approach offers the following benefits for your design process:

  • Improved communication – the ubiquitous language element makes for easier and simpler communication, especially between technical and non-technical members of the development team.

  • Aligned to your business goals – with clarity and consistency on the intended business results of the digital product you are more likely to create a product that reflects how your business operates.

  • Flexibility – with a layered and modular design, your product is easier to update, modify and modernize as the need arises, with less unintended impacts.

  • User-focused – although the domain is more fundamental, and in a sense therefore more important, than the user experience or user interface, nevertheless by keeping the domain central in the design process, the result is a product that addresses the needs of users for whom the domain is most relevant.

  • Efficiency – put simply, with the close (and comprehensible!) involvement of subject matter experts, the product is more likely to do the job it needs to do, as opposed to the job a developer might think it should or could do; i.e. there’s less likelihood of it having features that nobody will use!

All that said, it must be acknowledged that DDD requires extensive domain expertise and input. This may sound obvious but it can result in a lengthier (and therefore more expensive) design process. For complex products, or products operating in a complex domain, DDD is absolutely the most effective and efficient approach (especially when combined with an Agile methodology, such as scrum) but for simpler scenarios, well, it’s back to that sledgehammer and nut analogy.


resources:

  1. codeopinion.com/should-you-use-domain-drive..

  2. youtu.be/8XmXhXH_q90

  3. thedomaindrivendesign.io

  4. medium.com/ssense-tech/domain-driven-design.. (Good to read)

  5. boldare.com/blog/what-is-domain-driven-design