Domain-driven design series (2) -- Analysis of concepts, differences and uses of VO, DTO, do, and Po

Source: Internet
Author: User
ArticleDirectory
    • Feedback

Domain-driven design series (2) -- Analysis of concepts, differences and uses of VO, DTO, do, and Po

The previous article, as an introduction, illustrates the advantages of domain-driven design. Starting from this article, I will talk about the application of domain-driven design based on my own practical experience. This article mainly discusses some of the objects we often use: Vo, DTO, do, And po.

Because different projects and developers have different naming conventions, here I will first give a brief description of the above concepts. The names are just identifiers. We will focus on the concept:

Concept:

Vo(View object):A view object is used to display a layer. It encapsulates all data on a specified page (or component.

Dto(Data transfer object):Data transmission object. This concept comes from the design mode of J2EE. It was originally designed to provide coarse-grained data entities for distributed applications of EJB to reduce the number of distributed calls, this improves the performance of distributed calls and reduces network load, but here I usually refer to the data transmission objects between the presentation layer and the service layer.

Do(Domain object):A domain object is a tangible or intangible business entity abstracted from the real world.

Po(Persistent Object):Persistence object, which is a one-to-one ing relationship with the data structure of the persistence layer (usually relational databases). If the persistence layer is a relational database, each field (or several) in the data table corresponds to one (or more) attribute of the Po.

Model:

The following uses a sequence diagram to create a simple model to describe the location of the above object in a three-tier architecture application.

L The user sends a request (which may be a form), and the data in the form is matched to VO at the presentation layer.

L The presentation layer converts VO to the DTO required by the corresponding method of the service layer and transmits it to the service layer.

L The service layer first constructs (or recreates) A do according to the data of DTO, and calls the do business method to complete the specific business.

L The service layer converts do to the PO corresponding to the persistence layer (you can use the ORM tool or not), calls the persistence method of the persistence layer, and passes the Po to it to complete the persistence operation.

L for a reverse operation, such as reading data, it is also converted and transmitted in a similar way, omitted.

VoAnd DTODifference

You may have some questions (many of my projectsProgramMembers also have the same question): Since DTO is the object for data transmission between the presentation layer and the service layer, why do we still need a VO? Yes! For most application scenarios, the attribute values of DTO and VO are basically the same, and they are usually pojo. Therefore, there is no need to do this, but do not forget that this is an implementation-layer thinking, at the design level, vo and DTO should exist in terms of concept. Because there is a fundamental difference between the two, DTO represents the data to be received and returned by the service layer, VO represents the data to be displayed at the presentation layer.

It may be easier to understand using an example: for example, the service layer has a getuser method to return a system user, and one of the attributes is gender (gender). For the service layer, it is defined only in semantics: 1-male, 2-female, 0-Unspecified. For the presentation layer, it may need to use "handsome guy" to represent male, "beauty" represents women, and "secret" represents unspecified. Speaking of this, you may also refute the fact that the "handsome guy" is returned directly at the service layer? For most applications, this is not a problem, but imagine that if the customer needs to be allowed to customize the style, the performance of different styles for "gender" is different, or this service is used by multiple clients at the same time (different portals), and different clients have different requirements for the performance layer, so the problem arises. In addition, back to the design layer analysis, from the principle of single responsibility, the service layer is only responsible for the business and has nothing to do with the specific manifestation. Therefore, it returns DTO, there should be no coupling with the representation.

The theory belongs to the theory. Is it necessary to analyze the design-level thinking at the implementation level? The one-size-fits-all approach will often outweighs the loss. Next I will analyze how to make the right choice in the application.

VoAnd DTOApplication

The above is just a simple example to illustrate the conceptual differences between vo and DTO. This section will show you how to make the right choices in applications.

In the following scenarios, we can consider combining VO with DTO (Note: it is an Implementation Layer ):

L when the requirement is clear and stable, and the client only has one, there is no need to distinguish VO from DTO. At this time, Vo can be retired and a DTO can be used, why is VO retired rather than DTO? Back to the design layer, the responsibilities of the Service Layer should not be coupled with the presentation layer. Therefore, for the previous example, it is easy to understand that DTO is "gender, still cannot use "handsome guy". This conversion should rely on page scripts (such as JavaScript) or other mechanisms (jstl, El, CSS)

L even if the client can be customized, or there are multiple different clients, if the client can implement conversion using a certain technology (script or other mechanism), it can also cause VO to be retired.

Vo and DTO coexist in the following scenarios:

L opposite scenarios of the above scenarios

L for some technical reasons, such as a framework (such as flex) that automatically converts pojo to some fields in the UI, you can consider defining VO at the implementation level, this trade-off is entirely dependent on the comparison between the efficiency improvement of development and maintenance brought about by the use of the framework's automatic transformation capability and the reduction of development and maintenance efficiency caused by the design of more than one vo.

L if there is a "big view" on the page, and all the data that makes up this big view needs to call multiple services, multiple DTO will be returned for assembly (of course, this can also be replaced by a DTO that provides a one-time return of a large view at the service layer, but whether this method is appropriate at the service layer needs to be weighed at the design level ).

DtoAnd doDifference

First, there is a conceptual difference. DTO is the data transmission object between the presentation layer and the service layer (it can be considered as the protocol between the two ), do Is the abstraction of various business roles in the real world, which leads to the differences between the two in data, such as userinfo and user (for naming rules of DTO and do, see my previous blog post). For a getuser method, it should never return the user's password. Therefore, userinfo should have at least one password less than the user. In the field-driven design, as mentioned in the first series, do is not a simple pojo, and it has domain business logic.

DtoAnd doApplication

From the example in the previous section, careful readers may find the problem: Since the userinfo returned by the getuser method should not contain the password, the attribute definition of password should not exist, but if there is a createuser method at the same time, the input userinfo needs to contain the user's password. What should I do? At the design level, The DTO passed by the presentation layer to the service layer and the DTO returned by the service layer to the presentation layer are conceptually different, but at the implementation level, we usually seldom do this (define two userinfo, or even more), because this is not wise, we can design a fully compatible DTO, when receiving data at the service layer, it should not be set by the display layer (for example, the total price of an order should be determined by its unit price, quantity, discount, etc.), whether or not the display layer is set, the service layer ignores all data returned by the service layer. When the service layer returns data, the data (such as the user password) should not be returned, and the corresponding attributes are not set.

For do, there is another point to note: Why don't I directly return do in the service layer? This saves DTO coding and conversion for the following reasons:

L the differences between the two may result in inconsistent relations between each other. a dto may correspond to multiple do statements, and vice versa. Even the two have many-to-many relationships.

L do has data that should not be known to the presentation layer.

L do has a business method. If do is passed directly to the presentation layer, the presentation layer'sCodeThe service layer can be bypassed to directly call the operations that should not be accessed. This problem is particularly prominent for the access control mechanism based on the AOP interception service layer, the calling of do business methods at the presentation layer also makes it difficult to control transactions due to transaction issues.

L for some ORM frameworks (such as Hibernate), the "delayed loading" Technology is usually used. If do is directly exposed to the presentation layer, in most cases, the presentation layer is not within the scope of the transaction (opensession in view is not a highly respected design in most cases). if it tries to obtain an unloaded associated object when the session is closed, the runtime exception will occur (lazyinitiliaztionexception for hibernate ).

L at the design level, the presentation layer depends on the service layer, and the service layer depends on the domain layer. If do is exposed, the presentation layer directly depends on the domain layer, although this is still a one-way dependency, this cross-layer dependency will lead to unnecessary coupling.

For DTO, it must be explained that DTO should be a "Flat two-dimensional object". For example: if a user is associated with several other entities (such as address, account, and Region), do the userinfo returned by getuser () need to return the DTO of the associated object together? In this case, the data transmission volume will inevitably increase. For distributed applications, this design is more unacceptable due to data transmission, serialization, and deserialization on the network. If getuser needs to return an accountid, accountname, regionid, and regionname in addition to the basic information of the user, define these attributes in userinfo, A "three-dimensional" Object Tree "is squashed into a" Flat two-dimensional object ". The project I currently participate in is a distributed system, regardless of the system, converts all associated objects of an object into a DTO object tree with the same structure and returns the result, resulting in extremely slow performance.

DoAnd poDifference

In most cases, do and Po correspond one to one. Po only contains pojo of the get/set method. However, some scenarios still reflect the fundamental differences between the two in terms of concept:

L do does not require explicit persistence in some scenarios. For example, a commodity discount policy designed using the Policy mode will generate an interface for the discount policy and different implementation classes of the discount policy, these discount policies can be called do, but they only reside in static memory and do not need to be persisted to the persistent layer. Therefore, such do does not have the corresponding Po.

L likewise, po does not have the corresponding do in some scenarios. For example, there is a many-to-many relationship between Teacher and Student. In relational databases, this relationship needs to be represented as an intermediate table, which corresponds to a po of teacherandstudentpo. However, this Po has no practical significance in the business field and cannot correspond to any do at all. It should be specifically stated here that not all many-to-many relationships have no business meaning, which is related to specific business scenarios. For example, the relationship between two po will affect the specific business, in addition, there are multiple types of such relationships, so this multi-to-many relationship should also be represented as a do, for example, there is a multi-to-many relationship between "role" and "resource, this relationship is obviously represented by a do-"permission ".

L in some cases, for a persistence policy or performance consideration, a po may correspond to multiple do statements, and vice versa. For example, if the customer has its contact information contacts, there are two do statements in one-to-one relationship. However, due to performance considerations (in extreme cases, the permission is used as an example), in order to reduce the database connection query operations, merge the DO Data of customer and contacts into one data table. In turn, if a book has a cover property, but this property is binary data of an image, and some query operations do not want to load the cover together, this reduces disk I/O overhead. If the ORM framework does not support Attribute-level delayed loading, you need to consider separating the cover from a data table, in this way, a do corresponds to a po.

L certain Po attribute values have no significance for do. These attribute values may be data that exists to solve certain persistence policies. For example, to implement an optimistic lock, Po has a version attribute, this version has no business significance for do and should not exist in do. Similarly, do may also have attributes that do not require persistence.

DoAnd poApplication

As the functions of the ORM framework are very powerful and widely used, and Java ee has released the JPA specification, the current business application development basically does not need to distinguish do and Po, PO can be completely through JPA, hibernate Annotations/HBM is hidden in do. However, we must pay attention to the following issues:

L for do attributes that do not require persistence, You need to explicitly declare them through Orm. For example, in JPA, you can use @ transient to declare them.

L for attributes in Po that exist for a persistence policy, such as version, because do and Po are merged, they must be declared in do, however, this property has no business significance for do and needs to be hidden. The most common practice is to privatize the get/Set Method of this property, the get/set method is not even provided, but for hibernate, this requires special attention because when hibernate reads data from the database to do, the reflection mechanism is used to call the empty parameter constructor of do to construct the do instance, and then use the an standard to reflect the set method to set values for each attribute. If the set method is not explicitly declared, or setting the Set Method to private will cause hibernate to fail to initialize do, resulting in a runtime exception. The feasible method is to set the attribute's set method to protected.

L hibernate provides good support for scenarios where one do corresponds to multiple Po, one PO corresponds to multiple do, and the attribute-level delayed loading, please refer to the relevant information of hibnate.

So far, I believe everyone has a clear understanding of the concepts, differences, and practical applications of VO, DTO, do, And po. Through the detailed analysis above, we can also summarize the principle that the analysis design and implementation layers are completely two independent layers, even though the implementation layer can combine two completely independent concepts by some technical means, at the analytical design level, we still (at least in our minds) we need to clearly distinguish the concepts of independence from each other. This principle is very important for analysis and design. (the more advanced the tools are, the more numb we are ). The first series of blog posts introduced the advantages of the big singing field-driven design, but in fact, the field-driven design still has various restrictions in the real environment and needs to be used selectively, as I mentioned in the "Tian Qi's wisdom" blog, we cannot choose the so-called "Best Design" in an idealized manner forever. If necessary, we must dare to give up, because the most suitable design is the best design. Originally, the second blog in the series should be about the restrictions on driver design and how to use them selectively, but forgive me for my negligence. This topic will be added in the next series of blog posts, so stay tuned. Posted on 2010-05-27 Johnny. Liang read (1658) Comments (1) EDIT favorites category: System Design


Feedback

# Re: domain-driven design series (2) -- Analysis of the concepts, differences and uses of VO, DTO, do, And po; Xiaoxiang Zhenyu is very good and explained in detail. The idea ends with the idea. The actual application needs to be determined by various application scenarios. Always believe that "there is no best design, only the most suitable design ".
Come on! :) continue to look forward to your next blog. Reply to more comments

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.