Quickly understand the DDD domain-driven design architecture idea - basic articles | Jingdong logistics technical team

1 Introduction

This article will learn and introduce Domain Drive Design (DDD) for short, why we need Domain Drive Design, and its advantages and disadvantages. Try to use some easy-to-understand words to describe and explain Domain Drive Design. It will explain the implementation from the in-depth discussion. You can go to in-depth study and discussion after understanding the introduction or in the follow-up advanced and advanced chapters. I hope that through the introduction of this article, you can quickly understand DDD and have a basic cognition , DDD itself is a collection of theories. It is difficult to effectively implement DDD without accumulating theories. Just look at some code cases and start doing it. What comes out in the end is just a mere imitation, so don't be too ambitious. Finally, I hope that everyone can think more in their work, such as how to design the project you are responsible for if you use DDD, and what challenges you will face.

Before learning to understand DDD, I hope that everyone can review what we have learned in the past and master some knowledge, and try to let the content we have learned and mastered settle down. I recommend reading series.

  • Head First Design Patterns: Basic object-oriented concepts and important design patterns;
  • UML object-oriented modeling foundation: from requirements to analysis, from analysis to design, from design to coding, UML is useful
  • Realizing domain-driven design: very thick, more pragmatic, recommended reading
  • Domain-Driven Design: Zhang Yi-DDD's pioneering work, it is quite fantasy, and it will benefit a lot from reading it several times;

2 Definitions and concepts

Domain Driven Design (DDD) proposes a set of methodology from system analysis to software modeling. Convert business concepts and business rules into concepts and rules in the software system, thereby reducing or hiding business complexity and making the system more scalable to deal with complex and changeable real business problems. To sum up, it is a complete and systematic design method, a kind of design thinking, a methodology, not a "system architecture", a kind of architectural design principles and thinking.

2.1. Why use "Domain Driven Design", or what is its purpose and application scenario?

  1. Good at dealing with product development of highly complex businesses, which can help us refine a stable product core (called the core domain in the domain model);

  2. Modeling can improve the high cohesion of modeling, reduce the coupling degree between models, and improve the scalability and stability of the system;

  3. Emphasizing the cooperation and communication between the team and domain experts helps to establish a well-communicated team organization;

  4. Unified design ideas and design specifications help to improve team members' architectural design capabilities and object-oriented design capabilities;

  5. Existing microservice constructions follow the architectural principles of domain-driven design;

  6. If the software system you are responsible for is not complex, then you really don't need to learn Domain Driven Design!

2.2. What is the biggest difference between domain-driven design and the current popular architectural thinking?

The thinking of domain-driven design is: object + behavior + service, and all designs revolve around objects, behaviors, and services;

The current popular architectural design thinking is: vertical expansion based on the MVC layered architecture, and horizontal expansion of products by business modules;

2.2.1. The traditional solution

Three-tier application architecture: data-application (business logic layer)-presentation, usually based on data bits for database analysis and design.

  1. The service layer is too heavy, the data model loses blood, and there is nothing;

  2. Noodle-style programming or database-oriented programming, the service layer completes business logic around database operations, often in one line to the end;

3) The code is too heavy one by one, and it is difficult to expand and reuse;

  1. The database model is just a database mapping, without relevant behavioral support, and the behaviors are all completed by the upper layer Service, so it is a blood-losing domain model;

2.2.2. Domain-driven solution

The four-tier architecture disassembles the business logic in the three-tier layer into the application layer and the domain layer in the DDD layered structure, and sinks the core business logic performance to the domain layer for realization, with the business domain model as the core modeling (object-oriented modeling) , which can better reflect the abstraction of the real world, and its advantages are as follows

1) Light service layer + hyperemic domain model;

  1. The domain model encapsulates and implements its own behavior, which can be considered as a high cohesion and low coupling component;

  2. Since the model integrates data and behavior, it is a self-explanatory object with high code reusability and clear business logic;

  • User interface layer: The main responsibility is to display data information to the user through the user interface, explain the user's command at the same time, and send the user's request to the application layer.
  • Application layer: Complete data resource operation and business process arrangement by calling basic settings and domain layer, which is equivalent to BS layer;
  • Domain layer: The business logic is highly cohesive to the domain layer, so the domain layer is the core of the entire system, it is only related to the actual business, does not care about any technical details, and has nothing to do with persistence as much as possible;
  • Infrastructure layer: contains any type of framework, database access code or public methods, etc., a layer of pure technology;

2.3 How to learn domain-driven design

No one can achieve domain-driven design overnight. The so-called "connecting theory with practice", when first contacting or learning domain-driven design, there will always be an appeal to give formula-like design guidelines or specifications. It seems that software design is Like building blocks, as long as you follow the building process shown in the diagram, you can build the expected model without thinking. This seems unrealistic fantasy. To master domain-driven design, you must first understand and master some concepts and theoretical knowledge , on this basis, thinking about the principles behind these concepts, design principles, and thinking about the division of the boundary of the bounded context (Bounded Context), in fact, it is still the embodiment of the principle of "high cohesion and low coupling", but what content we consider is High cohesion, how to abstract to achieve low coupling, how to cooperate between layers in a layered architecture? How to decouple dependencies has emerged, and design decisions still need to be considered from the perspective of reuse and change.

3 Domain Driven Design

Domain-driven design emphasizes "domain" as the core driving force, and ensures the consistency between the domain model and program design through model-driven design. The domain model should not contain any technical implementation factors. The objects in the model truly express the domain concept, but do not Constrained by technical implementation, the domain model itself has nothing to do with technology, and domain-driven design is divided into strategic design and tactical design.

  • A domain is composed of one or more models;
  • A model is by definition an abstraction of a domain;
  • From the understanding, the general model can be considered as a high cohesion, low coupling component, module, or a subfield;
  • The model focuses on the modeling process, which will abstract a series of domain objects and domain services;
  • In DDD, a series of standard "domain elements" are defined for domain modeling; such as the tactical design metamodel

3.1. Strategy Design

Emphasize the key points of business strategy, how to allocate work according to importance, and how to do the best, follow the principle of large quantity:

  1. Design decisions must be guided so that interdependencies between parts are reduced, using design intent more clearly without losing critical interoperability and systemicity;

  2. The focus of the model must be on capturing the conceptual core of the system, the "vision" of the system.

3.1.1 Sub-domain division

A part of the entire business domain, focusing on the macro business, and dividing the large domain into smaller conceptual divisions between businesses, facilitates decision-making on how to allocate resources (people, money) during the system planning stage.

1) Core sub-domain: the most valuable and core part of the field, the key to product success or failure, and core competitiveness. In DDD development, focus on the core domain and give it the highest priority;

  1. Supporting subdomain: related functions that support the core subdomain in the project, focusing on a certain opposite side of the business;

  2. General subdomain: a cohesive subdomain that has nothing to do with the project intent, to solve some general problems, and any proprietary business should not be placed in the general subdomain;

3.1.2. Strategy Modeling

The focus is on the physical division of the system. Based on your domain segmentation results and the organizational structure of the company or department, you decide how to divide the subsystems, such as how to divide them, and how to interact with each other. This level often does not involve enough technical details for the time being.

1) Bounded Context (Bounded Context): Generally speaking, it refers to the modules in the system, the sub-services in the micro-service architecture, and the "package (Java)" or namespace (C#) in the monomer. It is a physical division of the system and limits the domain. The boundary of the model is introduced at a deeper level. This thing is divided into two words: boundary and context. It can be understood that at the beginning of system design, you need to draw a circle and set a range to ensure that the domain model is limited within this circle and cannot be crossed. field, this 'circle' is the bounded context.

  1. Common language: It is used to unify the language used by experts in the field, products, research and development, and testing to avoid problems such as inconsistency in understanding requirements, inconsistency between design and requirements, and poor communication. Can understand what is caused by each other, the scene is different, the same word will have different meanings.

  2. Context map: use graphs to express the relationship between bounded contexts, and the context map will be introduced in detail later, such as partnerships, anti-corrosion layers, big mud balls, etc.;

3.2. Tactical design

Depending on the domain model and the general oracle, the concepts in the domain model and the general oracle are mapped to the code implementation through the technical pattern. As the model evolves, the code implementation will also be refactored to better reflect the model concept.

  • mainly include:
  1. Represent concepts in the domain, such as entities, value objects, domain services, modules, etc.;

  2. Used to manage the life cycle of objects. Such as aggregates, factories, warehouses, etc.;

  3. For integration or tracking, such as domain events, etc.;

3.3. Explanation of terms

  1. Domain/Subdomain: What domain? In a broad sense, a domain is what an organization does and everything it includes. The domain can be large or small, and there are boundaries, not infinite, such as e-commerce, trading, shopping, etc. For example, we often hear customers say "We have such a few pieces of business" Generally speaking, the so-called "several pieces" here refers to subdomains.

  2. Entity: This word is widely used by us, even overused. Entity is an important concept. A typical entity should have 3 elements (identity, attribute, domain behavior), must have a unique identity, no identity An identified domain object is not an entity. Such as: User object is an entity.

  3. Attributes: The attributes of an entity are used to describe the static characteristics of the subject and hold data and state.

@Data
public class Product{
    private String sku;
    private String name;
    private Price price;
}


  1. Domain Behavior: An entity possesses domain behavior that better describes its dynamics as a subject. An object that does not have dynamic characteristics does not belong to domain behavior.
@Data
public class Product{
    private String sku;
    private String name;
    private Price price;

    //变更状态的领域行为
    public void changePriceTo(Price newPrice){
        //设计产品新加个
        .......
        
    }
}



  1. Value object (value object): It is relatively abstract, usually as an attribute of an entity. The difference between a value object and an entity is that a value object is immutable and has no unique identifier. It is only defined by the value of its attribute, and participation is its Judgment is based on value or identity, the former is a value object, and the latter is an entity;

A small example: the relationship between order items and orders: many-to-one, there are multiple order items in an order, and an order item will only appear in one order. Combination relationship, some parts cannot exist separately from the main body

public class Order {
    int id;
    User user;
}

public class OrderItem {
    private int id;
    private Product product;
    private int num;
    private Order order;
}


6) Aggregate root: In the aggregate, an entity needs to be designated as the aggregate root to serve as the external shock of the entire aggregate, that is to say, the outside can only access internal objects through the aggregate root. Such restrictions can maximize the internal objects Protect.

4 What is the value

The development of almost all projects has such a rule: the initial requirements are simple, and the complexity of the system is upgraded due to the surge in business in the middle and late stages, which leads to the need for drastic reform of the original design concept. Therefore, the more complex the system and the larger the code size, the greater the advantages of DDD. obvious.

  • Cooperative communication: emphasizing the cooperative communication between the team and domain experts, which helps to establish a well-communicated team organization;
  • Unified thinking: Unifying design thinking and design specifications helps to improve team members' architectural design capabilities and object-oriented design capabilities;
  • Flexible system: Through modeling, the high cohesion of the model can be improved, the coupling degree of model building can be reduced, and the scalability and stability of the system can be improved;
  • Product core: good at handling high-complexity business product development, which can help us refine a stable product core;
  • Business precipitation: The domain model is the core of the system and the direct precipitation of business in the domain, which has great business value.

5 Conclusion of the basic chapter

An important theoretical basis for the division of microservices is domain-driven design. However, due to the high threshold of DDD, many concepts, large and abstract systems, and the lack of practical experience and cases, many developers have a lot of doubts about DDD, or only stay in the I usually rely on searches or colleagues around me to talk about DDD. Through this article, I have a preliminary understanding of domain-driven design. In the early stage, we will briefly introduce it here. Later, we will share DDD from the code level to implement it.

Author: JD Logistics Bian Lei

Source: Reprinted from Yuanqishuo Tech by JD Cloud developer community, please indicate the source

The third-year junior high school student wrote the web version of Windows 12 deepin -IDE officially debuted, known as "truly independent research and development " . Simultaneously updated", the underlying NT architecture is based on Electron "Father of Hongmeng" Wang Chenglu: The Hongmeng PC version system will be launched next year, and Wenxin will be open to the whole society . Officially released 3.2.0 Green Language V1.0 Officially released
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/4090830/blog/10108142
Recommended