"System Architecture Design"-07-Domain-Oriented Technical Design

Article Directory

1 Entities and Value Objects

1.1 Entity Object

In object-oriented development, everything is an object. In domain-driven design, we focus on the entity (Entity) object rather than the data itself.

Entities should have two basic characteristics: unique identity and mutability.

1.1.1 Unique identification (Identity)

General strategy:

  • User provides initial unique value

The processing method depends on the user's input through the interface. The system judges whether it is repeated according to the user's input. If it is repeated, the entity is not allowed to be created.

  • The unique identifier is automatically generated within the system

This method is widely used in various scenarios that need to generate unique identifiers. Commonly, it is generated based on multiple methods such as time, IP, object identification, random number, and encryption.

  • The system relies on persistent storage to generate a unique identifier
    • Delayed identification
    • identify early

Example of delayed identification:

Delayed identification can use the function similar to the auto-increment primary key in the database

insert image description here

When we build the Project entity object, the object does not have a unique identifier, and the unique identifier needs to be persisted before it can be obtained.

Early identification example:

When the entity object is generated, the object already has a unique identifier

insert image description here

  • from another context.

Although this method is feasible, we do not recommend it in terms of implementation complexity.

1.1.2 Variability

Anemia model

insert image description here

  • Advantages
    Clear hierarchical structure, one-way dependence between layers, domain objects are almost only used as transmission media, and will not affect the division of layers.
  • Disadvantages
    Domain objects are only used for saving state or transferring state and do not contain any business logic. Objects with only data and no behavior are not real domain objects. All business logic is processed in the application layer. For fine-grained logic processing, a facade packaging effect is achieved by adding a layer of Facade. The application layer is relatively large, the boundary is not easy to control, and the dependencies between internal modules are not easy to manage. These are contrary to the division and integration of sub-domains and bounded contexts in domain-driven design, so we recommend the hyperemia model.

hyperemia model

The hyperemia model is more suitable for the design and development of more complex business logic

insert image description here

  • advantage
    • Object-oriented, the application layer conforms to a single responsibility. (It's too heavy to include all the business logic in an anemic model.)
    • Each domain model object generally has its own basic business method, which satisfies the characteristics of the congestion model.
  • Difficulties
    How to divide business logic. That is, it is difficult to correctly place business logic in the domain layer and application layer.

1.2 Value Objects

  • Value object features: with clear constraints, including that the value object is an immutable object, the value object has no unique identifier, and the value object has low complexity.

When we have extracted the entity object, we need to further sort out whether the entity contains potential value objects.

  • Value object extraction: as follows, we can think of it as a value object:

    • An object satisfies itself as a part of the measurement or description domain
    • can be used as an invariant
    • Combining different related properties into a conceptual whole
    • Can be replaced with another value object when the metric or description changes
    • Can be compared for equality with other value objects
    • When there are no conditions such as side effects on collaborating objects
  • extract example
    insert image description here

We found that the Customer object contains the customer's Address information, and Address is a value object, because Address combines Street, City, State and other related attributes into a conceptual whole; Address can also be used as an invariant. When the Address changes, it can be replaced by another Address value object.

1.3 Example (identifying entities and value objects)

Description: Take UserCenter as an example

1) Identify entity objects

The common language of UserCenter context to User includes:

  • User in the system must be authenticated
  • Users can process their own personal information, including name, contact information, etc.
  • User's security password and other personal information can be modified by the user

As above, it can be judged that User is an entity object rather than a value object

2) Extract the value object

  • User should contain a unique identifier ===>
  • The unique identifier of the User entity UserId may be just a database primary key value or a complex data structure ===>
  • We extract the UserId into a value object.

insert image description here

3) Mining key behaviors of entities

Considering that the user may leave the company and other reasons, the User can be in the activated or locked state, and the corresponding User entity application has activation (active) or lock (deactive) related behaviors.
insert image description here

4) Identify other value objects

  • User can modify password, name, contact information and other personal information ===》
  • PersonConcepts we can extract from User

Extracting information such as name and contact information from the User entity actually constitutes a concept of Person, which is a part of User.

  • Although Person is an entity, information such as Contact Info tends to be separated into value objects

insert image description here

5) Recognition result

Through the above analysis we get:

  • User and Person represent two entities
  • User contains Person implementation and UserId value object
  • Person contains PersonId, Name and ContactInfo value objects

1.4 Summarize the difference between entities and value objects

  • From the point of view of identification
    • Entities are uniquely identified
    • The value object has no unique identifier (there is no such value object or that value object)
  • whether read-only angle
    • entities are mutable
    • Value objects are read-only
  • From the point of view of life cycle
    • Entities have a life cycle
    • Value objects have no life cycle at all (need to be attached to a specific entity)

2. Domain Services

2.1 Concept

  • Domain service
    When an important process or conversion operation in the domain does not belong to the responsibility of the entity or value object, an operation as an independent interface should be added in the model, that is, domain service.

  • The difference from entities and value objects
    is that it performs a significant business operation process, and uses multiple domain objects as input for calculation, and the result often produces a value object for use by the application layer

Example: bank fund transfer scenario
Consider the bank fund transfer scenario in reality, the user enters the basic transfer-related information such as bank account and transfer amount through an ATM (Automatic Teller Machine, automatic teller machine), and the bank performs the transfer operation and sends a mobile phone message. From the perspective of architectural layering, the application layer obtains input from the user interface layer, sends messages to the domain layer and listens for confirmation messages, and decides whether to use infrastructure layer services to send notifications based on the operation results. If a notification needs to be sent, the infrastructure layer sends a mobile phone text message according to the instructions of the application. The key is that the domain layer needs to perform fund transfer operations. The service needs to interact with objects such as Account and Money, perform corresponding borrowing and lending operations, and provide confirmation of the results. The fund transfer domain service involving the cooperation of multiple domain objects in the domain layer is a typical domain service.

2.2 Example (extracting domain services)

Requirements: One of the requirements of the User entity in the UserCenter context is that user passwords must be encrypted, and plaintext passwords cannot be used.

  • Solution 1 (client encryption) [not recommended]
    • Operation: The client handles the encryption of the password, and then passes the encrypted password to the User
    • Disadvantages:
      • Client carries too much detail
      • Does not meet basic security design principles
  • Option 2 (User internal encryption) [not recommended]
    • Operation: User internally uses an encryption algorithm for encryption
    • Disadvantages: Does not conform to the single principle (User object only represents a user information, does not need and should not know too much encrypted information)
  • Solution 3 (extracting domain services) [recommended]
    • Operation: extract encryption operations into domain services, and expose them to domain objects through independent interfaces

For example, we can abstract an EncrytionService, and then use MD5 or other encryption algorithms to implement the interface.

3. Field events

3.1 Overview

  • Domain Events: Model the activities taking place in the domain as a series of discrete events.

A domain event is also a domain object and is an integral part of the domain model.

  • Domain Event Lifecycle
    • produce
    • storage
    • distribution
    • use

3.2 Domain event life cycle

insert image description here

The domain event framework provides three different processing methods around the domain event life cycle, and the
three event subscribers can be combined to form a complete processing process for event storage, distribution and use.

3.2.1 Simple Subscriber

A simple subscriber handles events directly, acting as an independent event handler, corresponding to the event's consumption phase.

3.2.2 Instant Forwarding Subscribers

  • Corresponds to the distribution and consumption phases of events
  • effect:
    • Functionality with Simple Subscriber
    • The event can be forwarded to other subscribers
      and the event forwarded to the message queue to meet the needs of remote subscribers

3.2.3 Event store subscribers

  • Corresponds to the storage and consumption phases of the event
  • effect:
    • Persisting events (like history) while processing them
    • Forwarded to the message queue through a dedicated event forwarder

3.3 Domain Event Modeling

3.3.1 Overview

  • Role:
    The identification of events sometimes has a certain degree of secrecy. When an entity depends on another entity, but there is no strong coupling between the two and the consistency between the two needs to be ensured, we can usually extract the event.

Example: We can identify Discussion entities based on common language. In order to avoid strong coupling between the Discussin context and the Core context, when a Discussion ends, the context needs to update the evaluation of the project and notify relevant interested parties. During this process, we can extract the DiscussionClosed event.

  • Field event naming: generally use the past tense to name events (such as the above-mentioned DiscussionClosed event)
  • Field event content
    • Uniquely identifies
    • generation time
    • event source
    • Other metadata, business data
  • domain event properties
    • Invariance in the strict sense (because events represent a transient state.)
  • Handling domain events: publish-subscribe style.

3.3.2 Examples

1) Publishing and subscribing to events

DomainEventPublisher and DomainEventSubscriber represent publishers and subscribers respectively. DomainEvent itself has a certain type, and DomainEventSubscriber subscribes to a specific DomainEvent according to the type

insert image description here

2) Timing diagram

Domain objects and interaction sequence diagrams involved in the publish-subscribe style

insert image description here

  • The application layer Application Service operates on an entity object to trigger the generation of domain events
  • Domain events are published through Domain Event Publisher
  • DomainEventSubscriber is created by Application Service as needed and subscribed and processed according to the event type.

3) Timing diagram (including storage)

Publish-subscribe sequence diagram with event storage

insert image description here

Domain events can be consumed by both local bounded contexts and remote bounded contexts. Issues such as the eventual consistency of messages, synchronization and asynchrony, and domain event storage need to be considered when publishing domain events in remote bounded contexts. Especially for various uncontrollable reasons such as network stability in remote interaction itself, events are generally stored for tracking and retrying when problems occur. Supporting different event types, supporting conversion between domain events and stored events, retrieving the history of all results produced by the domain model, and using data in the event store for business prediction and analysis are common event store requirements. Events can be stored centrally through Domain Event Publisher, or they can be stored in each Domain Event Subscriber separately. Build Event Store through Domain Event Subscriber for event storage.

4 Aggregate

4.1 Aggregation

4.1.1 Overview

  • Aggregation : A combination of a group of related objects, the smallest unit of data modification.

    That is to say, the modification of the object combination can only be done through the root entity in the aggregation, instead of directly modifying all entities in the combination.

  • The core idea of ​​aggregation : Minimize associations, help simplify traversal between objects, and use an abstraction to encapsulate references in the model.

  • Aggregated composition

    • Root (Root) entity, which is a specific entity in the aggregation
    • Describe a boundary, defining what is inside the aggregate
  • aggregate fixed rules

    • The root entity has a global id
    • External systems can only see the root entity
    • Only the root entity can be queried directly through the data, and other objects must be found through the traversal of the internal association of the aggregation
    • The delete operation must delete all objects within the aggregate at once

4.1.2 Examples

  • Object traversal graph without the concept of aggregation (left half of the figure)
    • Any object can interact in pairs, so the objects are all in the same boundary
  • Object traversal graph using the concept of aggregation (right half of the figure)
    • Divide the system into 3 boundaries by aggregating ideas
    • Each boundary contains an aggregate
    • The root object in the aggregate is directly associated with the outer boundary
    • Only root objects can interact directly, and other objects can only interact directly with the root object in the aggregate
    • 通过聚合可以把最多28-1次对象直接交互减少的23-1次

insert image description here

4.1.3 Aggregation and domain services

Looking back at domain services, using domain services is actually performing cross-aggregation operations, and the input object of domain services is the root entity object of each aggregation.

4.2 Aggregate Modeling

4.2.1 Flawed thinking

  • Idea 1 (aggregation-based modeling)
    • Classify Project, Task, and Plan as entity objects
    • Raise the Project to the root object of the aggregate

That is: the external system can only access the Plan and Task objects through the Project object, and the Project contains direct references to the Plan and Task.

insert image description here

  • Idea 2 (divided into three aggregates)
    • Project, Plan, and Task are divided into 3 different aggregates.
    • Extract the unique identifier of Project into a value object Project Id
    • Project is associated with Plan and Task objects through Project Id

insert image description here

4.2.2 Principles of aggregate modeling

1) True invariant conditions inside the aggregate

  • Principle
    Business rules should always be consistent, i.e. only one aggregate instance is modified in a transaction

    If all the content that needs to be modified in a transaction is in different aggregates, we have to reconsider the effectiveness of aggregate partitioning. While maintaining strong consistency within the aggregate, eventual consistency needs to be maintained between the aggregates.

  • Example
    In idea 2, the updates of Project and Plan are in the same transaction (that is, when updating Project, Plan should also be updated at the same time), so putting Plan into the aggregate with Project as the root entity is more in line with the principle of aggregate modeling.

2) Design small aggregates

  • Principle
    Prefers to use small aggregates

  • Interpretation

    • From a performance point of view,
      the complex object management and deep object traversal inside the aggregate will reduce the performance of the system
    • Scalability
      • The impact of system changes on large-grained aggregates is obviously greater than that of small aggregates
      • Considering that entities have life cycles and state changes, aggregate modeling also recommends using value objects first to reduce the internal complexity of aggregates.

3) Refer to other aggregates by unique identifier

  • in principle:
    • Make multiple aggregates work together by identity rather than object reference
    • The root entity in an aggregate should have a unique identifier
  • Example
    In Idea 2, introducing the value object Project Id as the unique identifier of the Project, and interacting with the root entities in other aggregates through this value object is a concrete embodiment of this principle. If the Task business is used as a root entity, a value object Task Id is generally extracted as its unique identifier.

4.2.3 Correct modeling ideas

After comprehensively applying the three principles of aggregation modeling, we can get the third idea of ​​aggregation modeling, which is the final result of our aggregation modeling of the above scenarios.

insert image description here

5. Repository

  • Resource library
    In domain-driven design, the resource library is actually the provider of the object, which can realize the persistence of the object

  • There are several points to note during the implementation of the resource library:

    • Each aggregate type corresponds to a repository (since operations on aggregates need to be maintained in a transaction).
    • When fetching an aggregate, we navigate the object starting from the aggregate root entity to control the aggregate bounds.
    • The requirements of the congestion model for data objects: prevent data-driven, avoid entities and value objects from becoming pure data containers.
    • Technical complexities of masking data access through a repository
  • The purpose of introducing the resource library pattern in domain-driven design:

    • Provide customers with a simple model that can obtain persistent objects
    • Decouple application and domain design from persistence technology, reflecting design decisions about object access

insert image description here

  • The repository can be divided into two parts:
    • Definition of repository
      • represents an abstract interface
      • at the domain level
    • Implementation of the resource library
      • Depends on the specific persistence medium
      • at the infrastructure layer

6 Integrated Bounded Context

6.1 Four mainstream integration modes

insert image description here

  • Including File Transfer
    • Disadvantage: how to update and synchronize files
  • Shared Database
    • Disadvantages: how to ensure a unified database schema
  • Remote Procedure Call (RPC):
    • Disadvantages: easy to generate bottleneck nodes
  • while messaging
    • Disadvantages: While providing loose coupling, it also increases the complexity of the system

6.2 Implementation of context integration

6.2.1 Overview

  • In domain-oriented strategy design, we mentioned that there are two basic modes of context integration:
    • Anti-corrosion layer
    • uniform agreement
      • The unified protocol model (for the services provided by the system) defines a set of protocols (including standardized data structures)
      • Develop the protocol to enable use by other systems requiring integration, while improving and extending the protocol as new integration needs arise
  • The HTTP method and the resources it represents are a unified protocol
    • The integration implementation mechanism of RESTful style is as follows:
URL HTTP method describe
http://www.liubei.com/users GET Get a list of User objects
http://www.liubei.com/users PUT Update a set of User objects
http://www.liubei.com/users POST Add a new set of User objects
http://www.liubei.com/users DELETE Delete all User objects
http://www.liubei.com/users/guanyu GET Get the list of User objects according to the username guanyu
http://www.liubei.com/users/guanyu PUT Update the User object according to the username guanyu
http://www.liubei.com/users/guanyu POST Add a User object with the username guanyu
http://www.liubei.com/users/guanyu DELETE Delete the User object according to the username guanyu

6.2.2 Examples of anti-corrosion layers

  • Precondition:
    In the UserCenter context of the case, users participating in the Discussion need to authenticate themselves through UserCenter. This process involves the integration between the two contexts
  • Integration solution
    • Provide RESTful-based UserResource in the context of UserCenter
    • The Discussion context can access the UserResource through basic HTTP requests for user authentication
    • A layer of anti-corrosion layer containing UserAdapter and UserTranslator components is added between the two contexts (to reduce system coupling)

Example of anti-corrosion layer

6.2.3 Message Passing Patterns

  • publish/subscribe model
  • peer-to-peer mode
    insert image description here

6.2.4 Core+Discussion context integration sequence diagram

  • need:

The Core context creates a Project, and the project's time plan is calculated by the Discussion context

  • Timing diagram
    insert image description here
  • Timing diagram description:
    • Core contexts can be created via the ProjectCreated domain event and published through the messaging system.
    • The Discussion context subscribes to and handles the event
    • Discussion sends the time plan of the project back to the Core context for processing through the DiscussionFinished event

7. Applications

7.1 User interface

  • User interface is not the focus of Domain Driven Design

  • questions that need to be clarified

    • How to render domain objects into the user interface
    • How to reflect user actions to the domain model
  • User interface and domain model decoupling pattern

    1. Data Transfer Object (DTO) pattern
      • Business Object (Business Object) is a business service that fills data for a transfer object, equivalent to a domain object
      • Transfer Object (Transfer Object), also known as a value object, only has methods for setting and getting properties
      • The client (Client) can send requests or send transfer objects to business objects
    2. Façade pattern
      • Provide a consistent interface for a set of interfaces in the subsystem, making the subsystem easier to use
      • Realize that the user interface is not coupled with the system, but the appearance class is coupled with the system
      • In a hierarchical structure, you can use the Façade pattern to define the entrance of each level in the system

insert image description here
In Domain Driven Design, we use Application Services to implement DTO and Façade like functionality.

7.2 Application Services

7.2.1 Positioning of application services

  • is a direct client of the domain model
  • Responsible for the coordination of business processes
  • Control transactions using repositories and decouple service output

insert image description here

7.2.2 The difference between application service and domain service

Application services usually do not include business, and appear as a very thin layer similar to Façade.

7.3 3.infrastructure

  • The definition of the repository is part of the domain model
  • A major function of the infrastructure is to provide the implementation of various resource libraries
  • Application services depend on the repositories defined in the domain model and are implemented using repositories provided in the infrastructure.
  • Use dependency injection to complete the resource library to achieve dynamic injection in application services
    insert image description here

8 Case Technical Design

8.1 Context Domain Model

8.1.1 Core domain

  • Its common language:

    • an item has priority
    • A project has many Tasks
    • The task of the project is to complete the decomposition of the task and the plan of the project
  • The domain model corresponding to its context is shown in the figure
    insert image description here

The two aggregate root entities, Project and Task, are the main domain models in the Core core domain. The corresponding domain events are generated around the creation of projects, the decomposition of tasks, status updates, and the formulation of final plans, while application services and resource libraries use a common naming structure with the two aggregates.

8.1.2 Discussion support domain

  • Its common languages ​​include

    • Get the plan through the meeting in Discussion
    • Members participating in Discussion must be legal members of the system
  • The domain model corresponding to this context is shown in the figure
    insert image description here

The main entity in this support domain is Discussion. At the same time, as the upstream of UserCenter in the integration context, the Discussion support domain adopts the anti-corrosion layer strategy for integration and decoupling.

8.1.3 UserCenter Scope

  • its lingua franca

    • Provides services for user registration and authentication by external systems
    • Support modifying basic information such as user's contact information and password
  • The domain model corresponding to this context is shown in the figure
    insert image description here

The UserCenter general domain involves the User aggregate root, the Person entity, and a series of value objects representing entity attributes. Operations such as User registration, password modification, and contact information are abstracted into domain events, while User verification and password modification are separately extracted as domain services because of interactions involving multiple objects. As the downstream of the Discussion support domain, the UserCenter general domain adopts a unified protocol strategy to expose the entrance of User verification

8.2 Context Integration

  • Use unified protocol and anti-corrosion layer integration mode to achieve integration between 3 contexts
    • The left half represents the integrated mode
    • The right half is the implementation scheme corresponding to the integrated mode
      insert image description here

After adopting the above integration mode and implementation means, the sequence diagram of the interaction between the three contexts:
insert image description here


Guess you like

Origin blog.csdn.net/xingzuo_1840/article/details/128909209