[Practice] The most complete [DDD domain modeling] Xiaobai study manual (attached at the end of the article) | JD Cloud technical team

guide

DDD domain modeling has been proposed and applied by manufacturers of all sizes, and everyone has their own understanding. This article is aimed at Xiaobai, systematically explaining what DDD is, what problems it solves, and some suggestions and practices. This article is mainly a kind of collision and sharing of ideas, hoping to inspire or help friends.

1 Introduction:

Under the environment at that time, monolithic applications were still the main body of the market, but large and complex software systems had emerged, which brought relatively large challenges to the team's design and development work.

DDD provides a new design idea. Through the division of business sub-domains and bounded contexts, a unified language that spans business and technology is established, and business and technology implementations are connected while modeling business.

The introduction of DDD theory has had a huge impact on the entire field of software architecture design, especially on the design of microservice architecture. So how do we use DDD to solve the large-scale business system problems we face?

Here we take the middle-end business as an example for practice and application.

Friendly reminder: Look at the catalog and look inside from the whole

2. Our current status:

2.1 Challenges faced by software design

• Uncertainty in software development runs through the entire life cycle of software engineering.

• There cannot be any "silver bullet" in software engineering to solve software complexity problems.

•The essence of software engineering is social engineering, and the competitiveness of an excellent team comes from mutual trust and good communication.

2.2 Complexity of software engineering:

• There is no way to avoid this complexity, only to control it. Over 20 years ago, top software designers realized that

• The importance of domain modeling and design. Although not explicitly stated, there is a new trend in the object community that Eric Evans calls Domain-Driven Design.

• Domain-Driven Design is a way of thinking and a set of priorities designed to accelerate the development of software projects that must deal with complex domains.

Original intention and goal: high cohesion, low coupling

3. Compared with traditional architecture design, the problems solved by DDD

Two core problems to be solved by DDD:

1. How to reasonably design the business architecture?

2. How to make the system architecture domain business architecture consistent and have sustainable expansion?

The basic goal of domain-driven design: effective modeling, and using the domain model to drive the team to communicate, analyze, design and develop.

4. The core idea of ​​domain-driven design:

1. Unification of model and real business

• Core interplay between models and program design. It is the close connection between the model and the implementation that makes the model useful and ensures that the analysis we do in the model translates into the final program.

• This tight coupling between model and implementation is also useful during maintenance and subsequent development, as we can interpret the code based on a rational understanding of the model.

2. Unify the (business and technical) language

• Models are the backbone of a common language used by all team members. Developers can use this language to discuss programs because of the association between model and implementation.

• They can communicate with domain experts without translation. And because the language is model-based, we can refine the model itself with the help of natural language.

3. Continuous learning of the team, digestion of knowledge, continuous development of the system

Models are condensed knowledge. The model is the organization method of domain knowledge agreed by the team and the method of distinguishing important elements. Through how we choose terms, decompose concepts, and connect concepts, models record the way we see the domain.

This common language (model) enables developers and domain experts to collaborate efficiently as they organize information into models.

4. Three principles of domain-driven design

P1: Focus on your core domain.

※ Focus on your core areas

P2: Iteratively explore models in a creative collaboration of domain practitioners and software practitioners.

※ Exploring the model through collaborative iteration

P3: Speak a Ubiquitous Language within an explicitly Bounded Context.

※ Unified language

5. Domain-driven design steps:

5.1. Unified language

The concept of the same object may be different in different contexts.

The domain is too complex, and it is only possible to form a unified language within the context of segmentation.

In the era when UML was the mainstream of modeling, software design was clearly divided into object-oriented analysis (OOA), object-oriented design (OOD) and object-oriented coding (OOP) phases.

In actual operation, the work of OOD is often undertaken by OOA and OOP respectively, and there are two separate models of analysis model and design model.

The core of domain-driven design is to establish a unified domain model . The domain model is at the core of the software architecture. During the software development process, the establishment of the domain model must be the center to ensure the faithful representation of the domain model.

To understand it simply, it means unifying the language of business personnel and developers , and using code to feel it is probably:

userService.love(Jack, Rose) => Jack.love(Rose)
companyService.hire(company,employee) => 
Company.hire(employee)

5.2. Event storms and command storms in the domain

Analysis process and method of domain modeling:

5.2.1. What is a domain event?

- Capture what happened in the domain we are modeling

"Any business event will leave footprints in the form of some kind of data. Our traceability of events can be done through traceability of data. ... You can't go back in time to see what happened what

However, on the basis of the documents, the scene of what happened at that time can be restored to a certain extent. When we arrange the footprints of these data in chronological order, we can almost clearly deduce what happened in the past period of time.”

Main points:

_ 1. Events that business cares about: _A domain event must be valuable to the business and help form a complete business closed loop, that is, a domain event will lead to further business operations.

2. Use the tense of "happened" to describe

3. There is a chronological order

5.2.2 、How to execute command storm?

Around the domain events identified in the first step, command analysis is carried out for each event. What command caused this event to occur.

Some commands may generate multiple events, you can use arrows to connect them

5.2.3. Find aggregation

5.2.3.1 What is Aggregation

Continue to explore

In domain-driven design, an aggregate is a group of related domain objects whose purpose is to ensure that business rules are executed in each life cycle of domain objects:

‣ Guarantee business invariant within the aggregation boundary

‣ Objects within the bounds can only be modified by the aggregate root

‣ Aggregate roots have a global identifier

5.2.4. Continuous exploration:

Domain-Driven Development emphasizes maintaining the conceptual integrity of the application model. But traditional DDD methods cannot be blindly applied to an infinite domain model without compromising the conceptual integrity of the model.

The method that really allows a model to scale to its greatest extent without sacrificing its conceptual integrity is called a "context". A bounded context explicitly defines the context in which the model applies. According to the organization of the team, the various parts of the software system

Set the boundaries of the model based on the usage of the component and the physical representation (code, database schema, etc.). Strictly maintain the consistency of the model within these boundaries without being disturbed and confused by issues outside the boundaries.

Create a global view of all model contexts by defining the relationships between different contexts.

6. Service division of DDD domain design

6.1 Repair Patterns (Legacy System Refactoring)

The "Fixer Mode" gradually "releases" the coupling degree of the existing system by stripping off new business and functions on the basis of the existing system assets, and solves the problem of unstable quality and many bugs in the legacy system. Improve traditional IT performance, make traditional IT services more stable and flexible, and reduce maintenance costs.

‣Repair mode is suitable for stock systems with infrequent demand changes

6.2 Strangling mode (legacy system refactoring)

The strangler mode" realizes digital IT innovation on the basis of existing system assets, and is more flexible in the face of innovative digital IT business. ‣By implementing new features in new applications, maintaining loose coupling with existing systems, only when necessary When the function is stripped from the original system, the original system is gradually replaced.

At present, the telemarketing system in China and Taiwan has adopted the strangle mode and has been restructured.

6.3 Principles of service division

According to business boundary context boundary division

‣ Realized high cohesion and low coupling at the business level ‣ In terms of granularity, it is more suitable for the ability of the team that has just started to do service-oriented architecture

‣ Divide according to organizational structure ‣ Divide services according to Conway's law

‣For teams with relatively mature technical capabilities, services can be split according to the identified aggregation relationship

In practice, different organizations are also applying the following service division principles

‣Split according to the frequency of change ‣The service can be divided according to the different frequency of change in the system function, usually

 来说,越靠近终端⽤户的特性变更频率越高,反之越低 

‣Divide the system according to the boundary of technological heterogeneity ‣Divide the system according to the development direction of different technology selection

‣Divided according to the different requirements of the business for scalability or robustness ‣Divided according to the different requirements of the enterprise for security

7. DDD panorama

1. Strategic Design

Strategic design will control and decompose the boundaries and granularity of tactical design, while tactical design verifies the validity, completeness and consistency of the domain model from an empirical perspective, and then iterates the previous strategic design stage in an evolutionary manner, thus forming a The iterative design process that spirals upward, as shown in the following figure:

2 tactical design

3. Panoramic view operation process

The design goals of the two different stages are consistent, they are a coherent process, and they guide and regulate each other, and finally ensure that an effective domain model and an expressive implementation evolve at the same time.

8. Domain Model

The revolutionary nature of DDD lies in the fact that the domain model accurately reflects the business language, while transactional programming models such as traditional J2EE or Spring+Hibernate only care about data. These data objects have no business methods except simple setter/getter methods, which are compared to blood loss models. .

There are several models, what is the difference between them? How should we choose? (Digression: Each has its own advantages and disadvantages. You need to find the balance point you expect, and don't use any one blindly.)

1. Model classification and characteristics

• Bleeding model: The model only includes data definition and getter/setter methods, and business logic and application logic are placed in the service layer. This class is called POJO in Java and POCO in .NET.

• Anemia model: Anemia model contains some business logic, but does not contain business logic that depends on the persistence layer. This part of the business logic that depends on the persistence layer will be placed in the service layer. It can be seen that the domain objects in the anemia model do not depend on the persistence layer.

• Congestion model: Congestion model contains all business logic, including business logic that depends on the persistence layer. Therefore, the domain layer using the congestion model is dependent on the persistence layer. The simple representation is UI layer->service layer->domain layer↔persistence layer.

• Bloating blood model: Bloating blood model is to put other application logic (such as authorization, transaction, etc.) that is not related to business logic into the domain model. I feel that the blood swelling model is another kind of blood loss model, because the service layer disappeared, and the domain layer did the work of the service layer, but nothing changed in the end.

2. Understanding of the 4 models

In the traditional development model based on the anemia model, the Service layer includes two parts, the Service class and the BO class. BO is an anemia model, which only contains data and does not contain specific business logic. Business logic is concentrated in the Service class. In the DDD development model based on the hyperemia model,

The Service layer consists of two parts, the Service class and the Domain class. Domain is equivalent to BO in the anemia model. However, the difference between Domain and BO is that it is developed based on the hyperemia model, which contains both data and business logic. And the Service class becomes very thin.

To sum up, the traditional development model based on the anemia model emphasizes Service over BO; the DDD development model based on the hyperemia model emphasizes Service over Domain.

•Advantages and disadvantages of anemia model:

Advantages of this model: 1. One-way dependence of each layer, clear structure, easy to implement and maintain 2. Simple and easy design, and the underlying model is very stable. Disadvantages of this model: 1. The part of the domain object is more closely dependent on persistence The domain logic is separated into the Service layer, which is not OO enough. 2. The Service layer is too thick

Advantages and disadvantages of hyperemia model:

The advantages of this model: 1. It is more in line with the principles of OO. 2. The Service layer is very thin and only acts as a Facade, not dealing with DAO. Disadvantages of this model: 1. DAO and domain object form a two-way dependency, and complex two-way dependency will lead to many potential problems.

2. How to divide the logic of the service layer and the logic of the domain layer is very ambiguous. In actual projects, due to differences in the level of designers and developers, the entire structure may be chaotic. 3. Considering the transaction encapsulation characteristics of the Service layer, the Service layer must provide corresponding transaction encapsulation methods for all domain object logics. As a result, the Service completely redefines all domain logic, which is very cumbersome, and the Service transactional encapsulation Its meaning is equivalent to transforming OO domain logic into process Service TransactionScript. The hyperemia model has worked so hard to implement OO in the domain layer, and it has become a procedural style in the Service layer.

From the perspective of Web layer programmers, there is no difference from the anemia model.

1. I don't want the transaction to be managed by Item, but by the container or a higher-level business class.

2. If the Item is not separated from the management of the persistence layer, such as JDO's pm, then itemDao.update(this); is unnecessary, that is to say, the Item is taken out from the database during the transaction process, and the statement period does not exceed the current the scope of the transaction.

3. If the item is separated from the persistence layer, that is, when the life cycle of the item exceeds the scope of the transaction, it must be displayed to call the persistence method such as update or attach. In this case, it should be according to what robbin said The second model to do.

Advantages and disadvantages of blood swelling model:

Advantages of this model: 1. Simplified layering. 2. It is also in line with OO. Disadvantages of this model: 1. Many service logics that are not domain logic are also forcibly put into domain objects, causing instability in the domain ojbect model. 2. Domain object exposure Giving too much information to the web layer can cause unintended side effects.

evaluate:

Among these four models, the blood loss model and hemorrhage model should not be advocated. Both the anemia model and the hyperemia model are technically feasible.

The first model is opposed by most people, so I will not talk about the reasons for the opposition. But unfortunately, the actual situation I observed is that many companies using Hibernate end up with this model,

There is a big reason for this is that the technical level of many companies has not reached this level, which led to the emergence of this anemic model. From this point of view, Martin Fowler's critical voice is not too loud, but too weak, and he needs to continue to shout.

The second model is the model that Martin Fowler has always advocated, and in fact we have been using this model in actual projects. But I think this model is still not perfect, because you still need a business logic layer to encapsulate all domain logic, which seems very wordy,

And the interface of the business logic object is not stable enough. If the reusability of business logic objects is not considered (the reusability of business logic objects cannot be good), many people simply remove the xxxManager layer and call xxxDao directly in the Action code of the Web layer.

At the same time, container transaction management is configured on the Action layer. Hibernate's caveatemptor is a typical application of this architecture.

The third model is a model that I am very opposed to. Under this model, Domain Object and DAO form a two-way dependency, which cannot be separated from the framework test, and the service of the business logic layer is also coupled with the state of the persistence layer object. Will cause a high degree of complexity of the program,

Very poor flexibility and poor maintainability. Perhaps this model will become an ideal choice if the domain object under the O/R Mapping management developed by technological progress in the future is sufficiently dynamic, durable and transparent.

Just like the popularity of O/R Mapping makes the second model possible Martin Fowler's Domain Model, or is our second model perfect? Of course not, then I will analyze its shortcomings and possible solutions.

(For detailed code examples and analysis, please refer to: https://my.oschina.net/u/1999167/blog/1841997 )

3. Why is the traditional development model based on the anemia model so popular?

As we said earlier, the traditional development model based on the anemia model separates data from business logic, which violates the encapsulation characteristics of OOP, and is actually a process-oriented programming style.

However, almost all Web projects are now based on this anemia model of development, and even the official demo of the Java Spring framework is written according to this development model.

4. The gains and losses of DDD complete hyperemia or hyperemia model

When talking about DDD, I often make an assumption: Assume that your machine has infinite memory and never goes down. Under this assumption, we don’t need to persist data, that is, we don’t need a database.

So how are you going to design your software? This is what we call Persistence Ignorance: persistence-independent design. Without the database, the domain model will be designed based on the program itself, and students who love design patterns can show their talents here. Among process-oriented, function-oriented, and object-oriented programming languages, object-oriented is undoubtedly the best way to model domains.

A class is a bit like a table (many people think that a table corresponds to a class, and a row corresponds to an object). Personally, I strongly disagree with this equivalence relationship. This perception directly leads to the lack of software design. significance. Classes and tables have the following significant differences,

These differences have significant differences in the expression richness of domain modeling. With encapsulation, inheritance, and polymorphism, our expression of domain models is much more vivid, and our compliance with SOLID principles will be much more rigorous.

Since the feature of domain modeling is no longer carried, the design of the database can become unconstrained, and any method that can speed up storage and search can be used. We can use column database, document database,

A very delicate intermediate table can be designed to complete the query of big data. In short, the thing to do in database design is to access as efficiently as possible, not to perfectly express the domain model (this statement is a bit reactionary, just take a look), so let's take a look at the architecture diagram:

Therefore: the ideal is very full, but the reality is very skinny. We cannot have infinite memory. In practical application, we must avoid the swelling of the model. Otherwise it will cause a lot of trouble.

9. Practice of domain-driven in business analysis of middle office

1. Application architecture specification in the DDD domain of the business platform

2. The vision of using DDD domain modeling in the business center (architecture layering)

3. Existing systems use DDD for domain analysis

4. Construction of data structure model boundary

Personal summary: DDD is just a methodology, and the DDD frameworks of various companies on the Internet are just a kind of practice and experimentation on the methodology according to your own understanding. So don't worry about what is a DDD framework and how to write a DDD framework.

Don't rigidly apply the various congestion and anemia models of DDD, the most important thing is to find a model that suits you and solve the modeling problem. DDD just provides you with a systematic methodology and nothing more, it's not very high.

Recommended tutorials and documentation:

Banqiao Dahua DDD briefly talks about some basic characteristics of DDD in vernacular, just literacy! Database SQL Strongman Cautious Entry

Banqiao's ten-year experience in DDD research: "The Way of Complex Software Design: Comprehensive Analysis and Practical Combat of Domain-Driven Design" thanks to the great love of Machinery Press

Banqiao: Why is DDD's Bounded Context translated as "Bounded Context"?

Banqiao: The problem space and solution space in DDD are a false proposition

Case of business code programming traps - Jaxenter's very common inappropriate programming methods, traps caused by blood loss model

Comparison of two analysis and design methods of object-oriented modeling and database modeling Database-driven design and object modeling are two schools that determine the fate of software. Who can make software more alive and more convenient for maintenance and expansion? More scalable?

Uncle Bob: Design the behavior of the object first, and then design the database table structure! Advice from Uncle Bob, software engineering guru and co-creator of Agile

Object-Oriented and Domain Modeling According to surveys, currently about 70% of programmers are using OO language to write traditional procedural software. The basic root cause is the lack of education and training of object-oriented thinking methods. This article discusses several common problems in software development. Questions present independent insights and poignant points of view

Evans DDD domain modeling How to refine the model instead of the data table, and then refine the model object so that it can reflect the basic essence of the domain concept is a complex process. Evans DDD is a revolutionary software idea proposed in 2004.

Practical DDD (Evans DDD: Domain-Driven Design Domain-Driven Design) domain modeling is an artistic technique, not a mathematical technique. It is a solution for complex software to quickly cope with changes.

Model Refinement of Domain Model-Driven Design (Evans DDD)

Software Modeling Design

How to discover rich engorged objects from responsibilities and collaborations? Blood loss model Anemia model is the biggest enemy of DDD, how to design business behavior according to SOLID principles and GRASP principles ? This article gives some specific details in the specific practice of DDD, which is a good way to cooperate with DDD to carry out object-oriented analysis and design.

Unified description of business model Unified language is an important feature and focus of DDD.

The case of DDD CQRS and Event Sourcing: A football game DDD + CQRS + Event Sourcing implementation case, combined with code and theory explanation.

The DDD case of the container fleet system is a practical consulting case of domain-driven design DDD implemented by the transportation system of a large port company in Shanghai.

DDD warehouse implementation: Spring Data JDBC tutorial

Consequences of Not Using DDD: Why Did We Stop Migrating to Microservices?

Case Study of Uncovering Hidden Business Rules Using DDD Aggregation: Business Implementation of Database Transactions

Moving towards domain-driven design: How to use DDD to realize the migration from monolithic to microservices to create a business platform or middle platform?

Large-scale case of DDD+ microservices: How does Uber transform from complex RPC microservices to DOMA, a microservice architecture oriented to the business domain?

How does Shopify, the world's largest e-commerce company, use DDD to realize the modularization of its single architecture?

More #DDD domain-driven design topics , domain event topics

Reference blog literature: (drinking water does not forget the well digger)

•Talking about MVC, MVP and MVVM architectural patterns: https://draveness.me/mvx

•Deshui's blog: http://deshui.wang/

• CRUD engineer promotion path: https://zhuanlan.zhihu.com/p/25442175

• Natural resistance of objects and databases: https://www.jdon.com/mda/oo-reltaion2.html

•Commands & Events instead of CRUD — Part 1: Commands:https://hackernoon.com/commands-events-instead-of-crud-part-1-commands-17f4c7aee33b

• Tang Xuehua's blog: https://www.cnblogs.com/netfocus/

•There is No U in CRUD:http://jlhood.com/there-is-no-u-in-crud/

•Event sourcing vs CRUD:https://community.risingstack.com/event-sourcing-vs-crud/

• Ali Hema domain-driven design practice: https://www.infoq.cn/article/alibaba-freshhema-ddd-practice

• DDD Strategy: Responsiveness of Architecture Design: https://zhuanlan.zhihu.com/p/30878497

• Use DDD to build your REST API instead of CRUD: http://blog.didispace.com/use-ddd-design-rest-api/

•DDD & co., part 1: What's wrong with CRUD:https://www.thenativeweb.io/blog/2017-10-25-09-46-ddd-and-co-part-1-whats-wrong-with-crud/

• The ultimate trick of DDD - By Experience: https://insights.thoughtworks.cn/ddd-by-experience/

•Overview of Domain Driven Design: http://zhangyi.xyz/overview-of-ddd/

•Refactoring from anemic model to DDD:https://blog.pragmatists.com/refactoring-from-anemic-model-to-ddd-880d3dd3d45f

• Why DDD is the best practice for designing microservices: https://www.jianshu.com/p/e1b32a5ee91c

• Practice of domain-driven design in Internet business development: https://kb.cnblogs.com/page/586236/

• Domain-Driven Design (DDD: Domain-Driven Design) https://www.jdon.com/ddd.html

My opinion on Domain Driven Design

Practice and Reflection of Domain-Driven Design

#DDD Case #DDD Bounded Context #DDD Aggregation

#DDD Entities #DDD Value Objects #DDD Services

#DDD warehouse mode #DDD Specification specification mode

#DomainEvents #EventStorming #CQRS Architecture

Author: Huang Xuebin, Jingdong Technology

Source: JD Cloud Developer Community

Clarification about MyBatis-Flex plagiarizing MyBatis-Plus Arc browser officially released 1.0, claiming to be a substitute for Chrome OpenAI officially launched Android version ChatGPT VS Code optimized name obfuscation compression, reduced built-in JS by 20%! LK-99: The first room temperature and pressure superconductor? Musk "purchased for zero yuan" and robbed the @x Twitter account. The Python Steering Committee plans to accept the PEP 703 proposal, making the global interpreter lock optional . The number of visits to the system's open source and free packet capture software Stack Overflow has dropped significantly, and Musk said it has been replaced by LLM
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/4090830/blog/10091788