Location>code7788 >text

Why I'm Getting More and More Into DDD - DDD Architecture Part (1)

Popularity:713 ℃/2024-10-30 18:21:53

Hello DDD

  1. DDD is a software design methodology, DDD is a means to guide us in doing software engineering design. It provides various types of techniques for cutting engineering models with, such as; domains, bounded contexts, entities, value objects, aggregation, factories, warehousing, and so on. With the guidance of DDD, we can invest more time upfront and plan more rationally for a sustainable iterative engineering design.
  2. There is a consensus set of engineering two-phase design tools in DDD, including: strategic design, tactical design
    • Strategic design, DDD architecture mainly responds to complex business system requirements, through the process of abstraction, partitioning, reasonable split into independent multiple microservices, so as to divide and conquer. With the evaluation of whether the split is reasonable or not, it is in the requirements of the development of on-line time, whether each time a large number of operations of multiple microservice development and on-line. Such a strategic design is a failed microservice monolithic design. So a handful of medium-sized monolithic applications surrounded by a service ecosystem makes more sense.
    • Tactical Design: In this category, the main focus is on how to express business concepts based on object-oriented thinking and using domain models. Often in architectures that don't do domain modeling, which is usually mapped to the MVC three-tier architecture, theService + Data ModelThe development model of the service will be flat, a large number of, flat out very complex business logic code. Coupled with the separation of behavioral objects and functional logic, the development of anemic models, so that the behavioral objects of the constant cross use, but also so that the system continues to increase the complexity, and to the root cause of the difficult to maintain. So this stage to design every model that can express the concept of the domain, and the use of entities, aggregation, domain services to carry.

Concept of DDD

What is the congestion model?

What is included in the field?

Entities, aggregates, value objects, what's the difference?

These concepts, too, are very important knowledge items in the tactical design process, and figuring them out is the only way to do DDD design.

congestion model

congestion modelThis refers to the aggregation of attribute information and behavioral logic of an object into a class, commonly used means such as providing within the object the current object'sInformation verificationPatchwork Cache KeyLogic processing without service interface callsetc.

  • This way you can get the information about the methods provided by an object when you use it, and all the logical methods that use the object don't need to deal with the same kind of logic again.
  • But don't just take the congestion model and limit it to the design of a class and the design of methods within a class. The congestion can also be the entire package structure, a package includes all kinds of components (models, storage, factories) needed to implement the package Service service, can also be regarded as the congestion model.
  • At the same time, we will then provide a similar class under the corresponding internal class, such as the user's real name, including, communication class, real name card, bank card, four elements and so on. They are written into a user class under the internal subclasses, so that in the code writing will also clearly see the subclasses belong to the information, easier to understand the code logic, but also easy to maintain the iteration.

domain model

domain model, refers to the abstraction and encapsulation of business rules, strategies, and business processes within a specific business domain. In terms of design means, domain modules are split by storm modeling to form bounded contexts. The biggest difference is to put the originalMany Services + Data ModelsIn the same way, it is split into separate bounded domain modules. Each domain creates its own belongings; domain objects (entities, aggregates, value objects), warehousing services (DAO operations), factories, port adapters Port (means of calling external interfaces), etc.

So, now here are a few concepts; Domain Services, Domain Objects, Warehouse Definitions, Event Messages, Port Adapters. Let's look at how they evolved from the anemic model before breaking down to explain each concept.

  • In the original Service + anemic data model development guidance, the Service calls each functional module in series. These infrastructures (objects, methods, interfaces) are called off each other. This is also because the anemia model does not have object-oriented design, all the requirements development only detailed design.
  • Changed to the congestive model, now we have a domain function for the aggregation, split a domain required Service for the domain service, VO, Req, Res redesigned as a domain object, DAO, Redis and other persistent operations for storage. For example; a set of account services, credit authentication, account opening, withdrawals and reductions, etc., each of which is an independent domain, in each independent domain, to create their own domain information required.
  • Another feature of the domain model is that it only focuses on the implementation of business functions and does not directly connect to any external interfaces or services. For example; will not directly call the DAO operation library, will not call the cache operation Redis, and will not directly introduce RPC to connect to other microservices. Instead, through the repository and port adapters, define the interface standards for calling external data with in/out reference objects, and let the infrastructure layer do the specific call implementation. In this way, the domain only cares about the business implementation, and at the same time do a good job of preservation.

Entity, Aggregate, Value Objects

Originally, development under the anemic model often didn't particularly care about the in- and out-reference objects of a method, and it was also often the case that many services shared a single VO object as an in-reference, as long as that object could bring in the property information I needed.

However, under the domain model design of DDD, the design of domain objects is very object-oriented. And the entire four-color modeling process for storm events is also being done in a domain object-driven manner.

The Entity, Aggregate, and Value objects, all three of which are located within the domain objects under each domain, serve the domain services within the domain. The three object definitions are specified below;

thing that has a material existence (as opposed a conceptual, virtual or online existence)

It is a domain object that is designed relying on persistence layer data guided by the functional goals of the domain service. The persistent PO object is an atomic class object without business semantics, while the entity object is an object with business semantics and unique identification, following the full life cycle object of the domain service method. For example; user PO persistent object, will cover, the user's account opening entity, credit entity, the amount of entity objects. It also includes the shopping cart entity object when placing an order for goods. This object is also usually the entry object of the domain service method.

  • Concept: Entity = Unique Identity + State Attributes + Behavioral Actions (Functions), is a fundamental building block in DDD that represents domain objects with a unique identity. An entity contains not only data (state attributes), but also associated behaviors (functions), and its identity remains constant throughout its lifecycle.
  • Characteristics:
    • unique identification: An entity has an identifier that can distinguish it from other entities. This identifier can be an ID, a composite key, or a natural key, the key being that it uniquely identifies the entity instance.
    • domain identifier: Entity identifiers are usually derived from business domains, e.g., user IDs, order IDs, and so on. These identifiers have business specific meanings and are unique in the system.
    • Appointment identification: In some cases, an entity's identifier may be automatically generated by an ORM (Object-Relational Mapping) framework, such as a self-incrementing primary key in a database. Such an identifier, while it may uniquely identify the entity, is not directly derived from the business domain.
  • Uses:
    • Expression of operational concepts: Entities are used to express specific business concepts such as users, orders, transactions, etc. in software. The characteristics and capabilities of these business objects can be described through the attributes and behaviors of entities.
    • Wrapping Business Logic: Entities not only carry data, but also encapsulate business rules and logic. These logics include verifying the validity of data, enforcing business rules, calculating attribute values, and so on. The purpose of this is to ensure the centralization and consistency of business logic.
    • Maintaining data consistency: An entity is responsible for maintaining its own state and data consistency. It ensures that its own attributes and associations are correct and complete at all times, thus avoiding data inconsistencies.
  • Means of realization:
    • Defining Entity Classes: Define a class in the code that contains the properties, constructors, methods, etc. of the entity.
    • Realization of unique identifiers: Provide the entity class with an attribute that uniquely identifies it, such as an ID, and ensure that this identifier remains unchanged throughout the entity's lifecycle.
    • encapsulated behavior: Methods that implement business logic in entity classes that manipulate the state of the entity and enforce relevant business rules.
    • Using the ORM framework: Use the ORM framework to map entities to database tables, which simplifies data persistence operations.
    • Realization of domain services: For cross-entity or cross-aggregation operations, domain services can be implemented to handle these operations rather than directly in the entity.
    • Using Domain Events: When the state of an entity changes, a domain event can be published so that other parts of the system can be notified to handle it accordingly.

value object

This object is immutable during the life cycle of the domain service method and has no unique identifier. It is usually used in conjunction with entity objects. Such as providing descriptions of object attribute values for entity objects, for example; a company employee's level value object, a four-level address information object for the receipt of an ordered product. Therefore, when developing a value object, you usually do not provide a setter method, but rather a constructor or builder method to instantiate the object. This object is usually not independent of the method as an input object, but do can be used independently as an output object.

  • Concept: A value object is composed of a set of attributes that together describe a domain concept. Unlike Entities, Value Objects do not need to have a unique identifier to distinguish them. Value objects are usually immutable, which means that once created, their state should not change.
  • Characteristics:
    • Immutability: Once a value object is created, its state should not change. This helps to ensure consistency and thread safety in the domain model.
    • Equality: The equivalence of value objects is not based on identities or references, but on the values of the objects' attributes. Two value objects are considered equivalent if all their attribute values are equal.
    • Replaceability: Since value objects are immutable, any operation that requires a change to a value object results in the creation of a new instance of the value object rather than modifying an existing instance.
    • focus on describing the state of things: Value objects are typically used to describe the state of things, rather than the unique identity of things.
    • Reusability: Value objects can be reused in different domain entities or other value objects.
  • Uses:
    • Amounts and currencies (e.g., prices, wages, fees, etc.)
    • Metrics and data (e.g., weight, length, volume, etc.)
    • Ranges or intervals (e.g., date ranges, temperature intervals, etc.)
    • Complex mathematical models (e.g., coordinates, vectors, etc.)
    • Any other set of properties that need to be encapsulated
  • Means of realization:
    • Defining immutable classes: Ensure that all attributes of a class are private and can only be set via the constructor.
    • Rewriting the equals and hashCode methods: This ensures that the equivalence of value objects is based on their attribute values, not on object references.
    • provide read-only accessors: Provides only methods for obtaining attribute values, not for modifying them.
    • Create instances using factory methods or constructors: This helps ensure the validity and consistency of the value object.
    • Consider serialization support: If the value object needs to be transferred over the network or stored in a database, serialization and deserialization support needs to be provided.

polymerization

Aggregate objects can be created when your operations on the database require the use of multiple entities. An aggregate object, which represents a database transaction, has transactional consistency. Entities in an aggregation can be provided by the aggregation to create operations, and entities are also referred to as aggregation root objects. An aggregation of an order will cover; the ordering user entity object, the order entity, the order detail entity and the order receipt four-level address value object. And that shopping cart entity object, which is the entry parameter, has been converted to an entity object. -- Transactional consistency within the aggregation and final consistency outside the aggregation.

  • Concept: An aggregation is a key concept in domain modeling, it is a set of cohesive related objects that work together to perform certain business rules or operations. An aggregation defines the boundaries of a set of objects that can be treated as a single unit for processing.
  • Characteristics:
    • Consistency boundaries: An aggregation ensures that state changes of objects within it are consistent. When operations are performed on objects within an aggregation, those operations must remain consistent across all objects within the aggregation.
    • root entity: Every aggregate has a Root Entity (Aggregate Root), which is the entry point to the aggregate. The root entity has a globally unique identifier, and other objects interact with the aggregation through the root entity.
    • Transaction boundaries: Aggregations also define the boundaries of transactions. Inside an aggregation, all change operations should be atomic, i.e., they should either all succeed or all fail, as a way to ensure data consistency.
  • Uses:
    1. 1.Wrapping Business Logic: Aggregation provides a clear business logic model by encapsulating related objects and operations together, which helps in the implementation and maintenance of business rules.
    2. 2.Ensuring Consistency: Aggregation ensures internal state consistency. By defining clear boundaries and rules, aggregation can enforce business rules internally, thus ensuring data consistency.
    3. 3.Simplifying complexity: Aggregation simplifies the complexity of the domain model by organizing related objects. This helps developers better understand and extend the system.
  • Means of realization:
    • Defining the Aggregate Root: Choosing the right aggregation root is the first step in implementing an aggregation. The root should be an entity that represents the entire aggregation and has a unique identifier.
    • Restricted access paths: Boundaries and consistency are maintained by only modifying objects within an aggregate via the aggregate root, and not allowing direct modification of the state of objects within the aggregate.
    • Designing Transaction Strategies: Achieve transactional consistency within aggregations to ensure that operations are either all completed or all rolled back. For interactions between aggregates, domain events or other mechanisms can be used to achieve eventual consistency.
    • Encapsulated business rules: Implement business rules and logic within the aggregation to ensure that all business operations follow these rules.
    • objectification: The aggregation root typically interacts with a data persistence layer to preserve the state of the aggregation. This usually involves object-relational mapping (ORM) or other data mapping techniques.

Storage and adapters

In the DDD design approach, the domain layer does so by only caring about the domain service implementation. This is best exemplified by the design of repositories and adapters. Typically, a repository and an adapter are found in theService + Data Modeldesign, various other external services such as Redis, RPC, configuration center, etc. are introduced in the Service. But in DDD, this part is decoupled through the definition of warehousing and adapters and infrastructure layers.

  • Characteristics:
    • Encapsulating persistence operations: The Repository is responsible for encapsulating all operations that interact with the data source, such as create, read, update and delete (CRUD) operations. In this way, domain layer code can avoid the complexity of dealing directly with databases or other storage mechanisms.
    • Collection management of domain objects: Repository is usually regarded as a collection of domain objects and provides methods for querying and filtering these objects, making it easier to get and manage domain objects.
    • Abstract Interface: The Repository defines an interface that is independent of the persistence mechanism, which allows the domain tier code to switch between different persistence mechanisms without modifying the business logic.
  • Uses:
    • Data Access Abstraction: Repository provides a clear data access interface for the domain layer , allowing the domain objects to focus on the implementation of business logic , rather than the details of data access .
    • Query and management of domain objects : Repository makes it easier and more flexible to query and manage domain objects , supporting complex query logic .
    • Separation of domain logic and data storage: With the Repository pattern, the domain logic is separated from the data storage logic, which improves the purity and testability of the domain model.
    • Optimizing data access: Repository implementations can include data access optimization strategies such as caching, batch operations, etc. to improve application performance.
  • Means of realization:
    • Define Repository interfaces: Define one or more Repository interfaces at the domain level that declare the required data access methods.
    • Implement Repository interfaces: Implement these interfaces in the infrastructure layer or data access layer, the specific implementation may be the use of ORM (object-relational mapping) frameworks, such as MyBatis, Hibernate, etc., or direct use of database access APIs, such as JDBC, etc..
    • Dependency Injection: Use Dependency Injection (DI) in your application to inject specific Repository implementations into the domain services or application services that need them. This further decouples the domain and data access layers and also facilitates unit testing.
    • Using the Specification Pattern: Sometimes, in order to build complex queries, it is possible to combine the use of the Specification Pattern, a pattern that allows business rules to be encapsulated into separate units of business logic that can be used by the Repository to build queries.

The Repository pattern is a core concept in DDD (Domain Driven Design) that helps keep the domain model focused and clear while providing a flexible, testable and maintainable data access strategy.

Warehousing decoupling means using a dependency inversion design, all the domain needs external services, not in the direct introduction of external services, but through the definition of interfaces, so that the infrastructure layer to implement the domain layer interfaces (warehousing / adapters) to deal with the way.

Then that means the base setup layer is responsible for the principle dockingcomprehensive database(computing) cacheconfiguration centerRPC interfaceHTTP interfaceMQ Pushand other resources, and undertake the interface of the domain services to call the services to provide data capabilities for the domain layer.

Also this will reflect the fact that the implementation at the domain layer has business semantics, whereas at the infrastructure layer there is no business semantics, it's all atomic methods. The domain business semantics are supported by a combination of atomic methods.

domain organization

In DDD, each domain is an independent result of bounded context splitting, and the realization of business process functions requires the linking of each domain module to provide a complete service of a whole chain. That is why it is often said that there is consistency of transactions within the domain and final consistency outside the domain.

At the same time these domain modules can be reused because they are independent. Under different scenarios with different functional requirements, different domain modules can be selected for assembly, and the process is like building blocks.

But there is a trade-off here, if the project is relatively not big and there is not much choreography to deal with. Then you can directly let the trigger layer dock to the domain layer, and coding will be more convenient after reducing the choreography layer.

flip-flop (electronics)

After all the models are defined, the domain business is strung together. Then the next step is to use it, and the ways to use it can include; interfaces (http/rpc), message listening, timed tasks, etc., which are uniformly defined as trigger actions.

Processing of calls to orchestration functions initiated by triggers. For example; timed task to do the credit's interest accrual, successful account opening message notification rebate coupon, provide interface for external calls to credit logic, etc.. These are all trigger actions.