"Domain-Driven Design series (2) - On the VO, DTO, DO, PO concept of difference and usefulness."

Domain-Driven Design series (2) - On the VO, DTO, DO, PO concept of difference and usefulness

 

This article discusses about some of the objects we often used: VO, DTO, DO and PO.

Due to the different projects and developers have different naming conventions, and here I first to be a simple concept above description, the name is just a logo, we focus on the concept:

 

concept:

VO (View Object ): a view object for display layer, it is the role of a given page (or component) of all of the data package together.

The DTO (the Data Transfer Object ): data transfer object, this concept comes J2EE design patterns, the original purpose is to provide a distributed application EJB data entity coarse-grained, in order to reduce the number of the distributed calls, thereby improving call distributed performance and reduced network load, but here, I refers to data transfer objects between the presentation layer and the service layer.

DO (Domain Object ): domain objects, is abstracted from the real world, tangible or intangible business entity.

PO (Persistent Object ): persistent object, with which the persistence layer (usually a relational database) data structure is formed one to one mapping relationship, if the persistence is a relational database, the data for each field in the table ( or several) on the PO corresponding to one (or several) properties.

 

model:

       A timing chart below to create a simple model to describe the position of the target in a three-tier application

 

 

l requesting user (fill out a form may be), to form VO data is matched in the presentation layer.

l VO to the display layer corresponding to layer into a service method as claimed in DTO, to the service layer.

The first layer l DTO service configuration data (or reconstruction) a DO, DO call business methods to accomplish specific business.

l DO service layer is converted to the corresponding persistence PO (ORM tool may be used, can not), the persistence persistence method call, it passes to the PO, persistence operation is completed.

l For a reverse operation, such as read data, is transmitted and converted in a similar manner, slightly.

 

VO and DTO difference

       You may have a doubt (I participate in the project, many programmers have the same doubts): Since DTO is subject to transfer data between the presentation layer and the service layer, why do we need a VO it? Correct! For most of the scenarios, the property values ​​of DTO and VO is basically the same, and they are usually POJO, so no need to bother, but do not forget that this is achieved the level of thinking, the design level, the concept of or should exist on VO and DTO, because both are essentially different, DTO represents the service layer needs to receive the data and return data, and data presentation layer represents the VO to be displayed.

       An example will be described may be more easily understood: the service layer, for example, a method of getUser system returns a user, a property which is gender (Sex), for the service layer, the definition of only semantically: 1- Male , 2 female, 0-unspecified, and for the presentation layer, it may need to use "male" for male, with "beauty" for women, with a "secret" for unspecified. Here, you might also argue, direct returns "hotties" in the service layer is not on line yet? For most applications, this is not a problem, but imagine if demand allows customers to customize styles, and different styles for "Sex" is not the same performance, or the service at the same time for multiple clients using (different portal ), and different requirements for client presentation layer are different, then the problem came. Again, back to the design level of analysis, from a single responsibility principle point of view, the service layer is responsible only for the business, irrespective of the particular form of expression, therefore, it returns the DTO, should not be coupled with the emergence of forms.

       Theoretical return theory, which in the end is the level of analysis and design thinking, do we have to do so at the level it achieved? One size fits all approach is often not worth the candle, I'll analyze the following applications how to make the right choice.

 

VO and DTO applications

       The above are just used a simple example to illustrate the difference between VO and DTO in concept, this section will tell you how to make the right choice in the application.

       In the following scene before we can consider VO and DTO two-in-one (note: to achieve levels):

l When the demand is very clear and stable, and the client is very clear there is only one time, there is no need to distinguish VO and DTO area, VO can retire at this time, you can use a DTO, VO Why is retired and not DTO? Back to the design level, the duties of the service layer and the presentation layer should not still be coupled, so, for the previous example, you can easily understand, DTO for "sex", it still can not use the "hotties", the conversion should depend 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 client, if the client is able to achieve some kind of conversion technology (script or other mechanism), it can also make VO retire

 

The following scenarios need to give priority VO, DTO co-exist:

l opposite scenario above scenario

When l for some technical reasons, such as a framework (such as Flex) provides POJO automatically convert certain UI Field, consider the definition of a VO at implementation level, this trade-off depends entirely on the ability to use automatic conversion framework to bring development and maintenance efficiencies than the decline between development and maintenance efficiency and design bring the VO do one more thing.

L If all of the data page appears a "large view", which consists of the large view of the need to call a plurality of services, a plurality of return assembled DTO (of course, it can also provide a large view of a disposable return DTO be substituted by a service layer but in the service layer to provide such a method is appropriate, need to balance the design level).

 

DTO and DO distinction

       The first is the conceptual distinction, DTO is data transfer objects between the presentation layer and the service layer (may be considered to be an agreement between the two), while DO is an abstraction of the real world a variety of business roles, which leads to two by differences in the data, such as UserInfo and user (for naming DTO and DO, see the author's earlier blog post), for a getUser method, it should never return the user's password in nature, and therefore UserInfo a password data at least one less than the User. In domain-driven design, just as the first article in the series said, DO is not a simple POJO, it has areas of business logic.

 

DTO and DO application

       From an example, the careful reader may find the question: If the method returns UserInfo getUser should not contain password, then it should not exist in this attribute defines the password, but if there is a method createUser the same time, incoming UserInfo need to include the user's password, how do? In the design level, the presentation layer transferred to the service layer and the service layer DTO DTO returned to the presentation layer in the concept is different, but in the implementation level, we usually rarely do (define two UserInfo, or even more) , because it does not seem very wise, we can design a fully compatible DTO, when the service layer receives the data, property should not be set by the presentation layer (such as the total price of the order should its price, quantity discount and other decisions), regardless of whether the setting presentation layer, service layer are not and will ignore, and in return the service layer data, data (such as user passwords) should not go back, do not set the corresponding property.

       For DO, the more thing: Why not return to direct the service layer DO it? Such encoding can be omitted and conversion work DTO for the following reasons:

L The difference in nature and may cause not correspond to each other, a DTO may correspond to multiple DO, and vice versa, even the two-many relationship exists.

l DO have some presentation layer should not be allowed to know the data

l DO have a business method, if passed directly to the DO to the presentation layer, layer to show the code can bypass the service layer calls directly manipulate it should not have access, for the mechanism for access control based AOP intercept service layer, this the problem is particularly prominent in the presentation layer DO call a business method will be because the problem transaction, so the transaction is difficult to control.

For some l ORM frame (e.g., the Hibernate), the often use "lazy loading" technique, if the DO directly exposed to the presentation layer, for the most part, the presentation layer is not within the scope of a transaction (Open session in view large in some cases not a design worthy of praise), if it attempts to get the case closed Session object associated unloaded, an exception (for Hibernate, it is LazyInitiliaztionException runtime) will appear.

l From the design perspective, the presentation layer depends on the service layer, service layer depends on the domain layer, if exposed to the DO, will lead the presentation layer is directly dependent on the field level, although this is still a one-way dependence, but this cross dependent layer will cause unnecessary coupling.

 

For DTO, there is also little to be explained, is the DTO should be a "flat two-dimensional object", give an example to illustrate: If you associate a number of other entities (such as Address, Account, Region, etc.) User will then getUser () returned UserInfo, whether it is necessary to DTO objects that are associated together to return it? If so, inevitably lead to increase the amount of data transmission, for distributed applications, since the transmission data over the network directed, serialization and deserialization, this design is more unacceptable. If getUser addition to the basic information of the User return, but also a need to return AccountId, AccountName, RegionId, RegionName, then, to make these attributes define the UserInfo, to a "three-dimensional" object tree "collapsed" into a "flat the two-dimensional object, "the author of the project is currently involved in a distributed system that willy-nilly, all associated objects are converted to an object DTO object tree and return the same structure, resulting in very slow performance .

 

 

DO and PO difference

       DO and PO in most cases is one to one, PO containing only POJO get / set methods, but some scenes still reflect the difference between the two concepts exist in nature:

l DO in some scenarios do not require explicit persistence, for example, by discounts on merchandise strategy pattern design policy, the policy will be derived discount Discount different interfaces and implementation classes, these classes can be regarded as a discount policy implementation DO, but they only reside in static memory, need not persisted to the persistence, so that such is not the corresponding PO DO exist.

l Similarly, in some scenarios, PO no corresponding DO, for example, the presence of many-teachers and students Teacher Student, in a relational database, the performance of the relationship requires an intermediate table, it corresponds to a TeacherAndStudentPO the PO, but this PO do not have any real significance in the field of business, its totally not correspond with any DO. It must declare that not all many relationships have no business meaning, which with about specific business scenarios, such as: the relationship between the two PO affect specific business, and there are many types of this relationship, then this many relationships should also be expressed as a DO, Another example: many relationship exists between "role" and "resources", and this relationship is clearly manifested as a DO-- "privilege."

L In some cases, for some persistent policy or performance considerations, PO may correspond to a plurality of DO, and vice versa. Such as customer Customer Contacts have their contact information, here are two DO-one relationship, but perhaps due to performance considerations (in extreme cases, the right for example), in order to reduce connection query the database, the Customer and two Contacts DO data incorporated into a data table. Conversely, if a Book Book, there is a cover cover property, but the property is a picture of binary data, but some queries do not want to cover operating load together, thereby reducing the overhead of disk IO, and assuming ORM framework does not support attribute-level lazy loading, then we need to consider the cover to a separate data table to go, thus forming a DO to deal with a case of the PO.

Some attribute values ​​for l PO DO not make any sense, these property values ​​may be in order to address some persistence strategy and existing data in order to achieve "optimistic locking", PO presence such as a version attribute to the version for DO said there is no business sense, it should not exist in the DO. Similarly, DO also may not require the presence of persistent attributes.

 

DO and PO applications

       Since the function ORM framework is very powerful and popular, but also introduced a JavaEE JPA specifications, current business application development, basically you do not need to distinguish between DO and PO, PO entirely by JPA, Hibernate Annotations / hbm hidden in the DO. Nevertheless, we must also pay attention to some problems:

l DO For unnecessary persistent attributes need to explicitly declare the ORM, such as: In JPA may be utilized @Transient statement.

l For the PO in order to some persistence strategy exists properties, such as version, due DO, PO merger must be declared in the DO, but because of this property of DO is not any business sense, we need to let the Foreign property Hide up, the most common practice is to get the property / set methods of privatization, does not even provide get / set methods, but for Hibernate, this requires special attention, due to Hibernate reads data from the database to convert DO, is using reflection to invoke instances DO DO null argument constructor function, and then using a JavaBean specification of reflecting the set methods for each property value is set, if not set explicitly declared method, or a method to set the private, are unable to initialize Hibernate lead to DO, so abnormal and feasible approach is to set the property is protected method set to run the event.

l for a corresponding number of PO DO, DO, or a PO corresponding to a plurality of scenes, and property level lazy loading, Hibernate provides good support, please refer to relevant information Hibnate.

 

 

    So far, I believe we have a clearer understanding of VO, DTO, DO, PO concept, the difference and the practical application. A detailed analysis above, we can summarize a principle: analysis and design level to achieve the level of two completely separate levels, even though the level achieved by some technical means can be two completely separate concepts into one, in analysis and design level, we are still (at least in their minds) need to distinguish clearly the stuff on the concept of independent district, this principle is very important (the more advanced tools, we tend to make more numb) to do analysis and design. First in a series Bowen initiate singing domain-driven design advantages, but in fact, domain-driven design in the real world there are all sorts of restrictions, require the use of selective, as I mentioned in the "Tianqi wisdom" Bowen, we can not always ideal to choose so-called "best design", if necessary, we still have to dare to give up, because is the best design the most appropriate design. Originally, the second in the series Bowen should be designed to limit the discussion to receive driver and how selective use, but please forgive my negligence, under a series of blog posts will make up this topic, so stay tuned.

Author: Cat Qi
Source: http://qixuejia.cnblogs.com/
This article belongs to the author and blog Park total, welcome to reprint, but without the author's consent declared by this section must be retained, and given the original connection in the apparent position of the article page, otherwise the right to pursue legal responsibilities.
 

Guess you like

Origin www.cnblogs.com/cx2016/p/12164347.html