dto– core data in service implementations

Source: Internet
Author: User

In the implementation of a Web service, we often need to access the database and display the data obtained from the database in the user page. One problem with this is that the data that is used to present on the user page and the data that is obtained from the database are often very different. In this case, we often need to send multiple requests to the server to get the data that will be used to display on the page.

One way to solve this problem is to use different data representations based on different requirements. The more common form of data representation in a service implementation is Mo (Model Object, also known as Vo,value object in some contexts) and DTOs (Data Transfer object). Mo is used to represent data that is read from a database, while a DTO is used to represent data transmitted over the network.

In this article, we will discuss how to use DTOs and Mo in the implementation of a Web service and simply introduce some other related data representations, such as view model.

Why DTO?

Whether it's a desktop app or a Web service, its internal data performance is important. When a beginner understands a system, it first needs to understand the role of each component in the system, and then understand the workflow in the system, that is, how each component works together when the business logic is executed. After understanding the two parts, the first thing the beginner needs to do is to comb through the details of how the data flows throughout the system, that is, the process of organizing and understanding the data flow (Dataflow). After a real understanding of the data flow, the beginner has the ability to develop in the system.

The process of organizing a data flow is a process of refinement: from identifying the data structure to how each property in the data structure is used. In the entire data flow, any change in the value of a property can result in a change in how the data is processed.

What do we do when we organize the data flow? First we need to identify what data will be transferred between components, what transformations are made during the transfer process, how the data is built, what data it is building, and ultimately whether the data is persisted to local storage and so on.

In the process of collating data flow, data conversion is often the most difficult part to understand. The definition of a data type is often related to its operating environment. For example, in an ecommerce site, a class product that represents a product may contain all the information about the product: The name of the product, the brand, the details, the price, and so on. This information will be displayed on the page when the user is browsing using a computer browser. But when users use their mobile phones for browsing, we need to consider how to save traffic to these mobile phone users. A way to save the user's mobile phone traffic is to display the product's brief information first, and then download the details of the product from the server when the user decides to view the detailed description of the product. In this case, the class product that contains all the information for the product will no longer be a data structure suitable for transport.

The problem is more likely to occur in the case of data consolidation if the data structure needs to be split. For example, the UE of a Web page, in order to improve the user experience, requires that the product brand details be displayed directly on the page. In this case, we need to add a domain brand that records the branded product in the class product that represents the product. But in the database, the class product that represents the product may simply record the brand ID of the product. So in the business logic, we need to merge the product with its corresponding brand.

We can even make things a little more complicated:

In the above figure, we show the many different forms of data that may exist in a system. In the center of the picture is a server where a variety of clients will get product information. As mentioned earlier, to save client traffic, the data sent to the mobile client by the server will be a short version of the product information on the server. When a browser accesses the product, the information that represents the brand is embedded in the product information to provide a better user experience. In addition to communicating with the client, the exchange of information may also be generated between the server. In this exchange process, product and brand branding are passed on to each other independently of the server. In the case of an agent running at the far end, it may only need a product ID to monitor the production status of the products.

All of this data should be obtained from the database of the system. Data in a database cannot be stored and maintained at the same time, so in a complex system, the data representation in a database is often a different data structure from the data transmitted in the system. The common case is divided into two categories: one for accessing the database, performing the data recorded in the database in the system, called Mo, the Model Object, and the other class is used to transmit in the network, called the DTO, that is, the data Transfer Object.

in the service DTO and the MO

After understanding why we need different representations of data such as DTOs and Mo, let's look at how this data represents how it works in a Web service.

Let's start with the simplest layering of web services. One of the simplest Web services consists of a data access layer (DAL), a business logic layer, and a three-part presentation layer. Where the presentation layer is running on the client side, while the other two levels run on the server. When data is read from the DAL layer, the data it records is consistent with the data recorded in the database, so they are the MO that we discussed in this article. When transferred to the client, the data may be different from Mo, so it is a dto:

Now let's zoom in on the data access layer to see where Mo is located in the data Access layer:

The first thing to emphasize is that there are many ways to implement the data access layer, and the only implementation that is based on the repository pattern is shown. Using repository to implement DAL is one of the most common implementations of data access layers. As shown, in an implementation based on the repository pattern, the data access layer will have a series of repository instances. These repository instances rely on the ORM used by the system to convert the data in the database into Java class instances. These Java class instances are actually the MO that the data access layer provides to the business logic layer.

DTOs are used to transfer data between services and customers, as well as between services and services. In these delivery processes, the need for DTOs can be varied:

The above image shows the process of interacting with a product of this type of dto between the server and the client and the server side. In this process, the dtos that need to be passed are not the same: when you use a browser to read and save information about product, there may be some subtle differences in the data representation of the two. After the save is complete, the service may send the new product as a payload to the other servers, and the product used at this point may be slightly different from the first two. If you define many different dtos for these subtle differences, the system can run into a series of problems with managing the data. For example, in a complex system, DTOs may flow in the system as follows:

In, we show a case where a DTO is circulating too many services in turn. If different dto representations are used in a DTO-by-pass process, the DTOs required by one service may not match the DTOs that are owned by another service. This is one of the simplest examples of how dtos can in turn affect architectural design, but it is also the most common problem in DTO management, which is that dtos are too expressive. If you create a dto for all of the different needs, a concept that corresponds to a dto can be as many as 5, 6, and very difficult to manage. This administrative difficulty often exists in how to specify the kinds of DTOs that a service needs to use, as well as in situations where you need to modify a series of dtos while changing a dto.

To prevent DTOs from deriving too many types due to different requirements, service implementations often allow the data in a DTO to contain some redundancy.

Step into adding your DTO

So how do we add dtos to the system? The answer is, as the case dictates. At the beginning of the project, the data stored in the database is often consistent with the data that the page needs to display, so we don't need the help of the DTO in this case. And when the data needed is no longer the same as the data that is recorded in the database, we need to consider whether we need to add a DTO to the project. Software developers need to ask themselves if the data that is needed is inconsistent with the data in the database, does it often occur? If the answer is yes, then we need to start preparing to add support for the DTO.

Adding a DTO to the system is mainly done in the following parts of the work:

    1. Add a DTO class.
    2. Add conversion logic from Mo to DTOs.
    3. Converts the original use of MO to the use of DTOs.

I believe that the first thing readers notice is the 3rd. As you can imagine, if you replace the whole system's MO with a dto, it will have a very large impact surface and is very prone to error. So in a large project, we often need to prejudge the need for DTOs to add DTOs as early as possible.

Let's take a look back and see how the first task should be done. In a system, DTOs are often used to transmit data, so they tend to have no logic on their own. This is why these dtos are often defined as JavaBean. The great benefit of defining dtos in the form of JavaBean is that many third-party libraries provide the ability to generate JavaBean. In this case, software developers only need to describe these dtos in a series of descriptive languages. The most common of these is JAXB.

When using JAXB, software developers only need to write a series of descriptive information in the. xsd file:

1 <Xsd:complextypename= "Address">2   <xsd:sequence>3     <xsd:elementname= "Name"type= "Xsd:string"/>4     <xsd:elementname= "Street"type= "Xsd:string"/>5     <xsd:elementname= "City"type= "Xsd:string"/>6     <xsd:elementname= "State"type= "Xsd:string"/>7   </xsd:sequence>8   <Xsd:attributename= "Country"type= "Xsd:nmtoken"fixed= "US"/>9 </Xsd:complextype>

Then after JAXB runs, the corresponding Java type will be generated:

1 @XmlAccessorType (Accesstype.field)2@XmlType (name = "Address", Proporder = {3"Name",4"Street",5"City",6"State"7 })8  Public classAddress {9     protectedString name;Ten     protectedString Street; One ... A @XmlAttribute -@XmlJavaTypeAdapter (Collapsedstringadapter.class) -     protectedString Country; the  -      PublicString GetName () { -         returnname; -     } +  -      Public voidsetName (String value) { +          This. Name =value; A     } at  -      PublicString Getstreet () { -         returnStreet; -     } -  -      Public voidSetstreet (String value) { in          This. Street =value; -     } to ... +      PublicString getcountry () { -         if(Country = =NULL) { the             return"US"; *}Else { $             returnCountry;Panax Notoginseng         } -     } the  +      Public voidsetcountry (String value) { A          This. Country =value; the     } +}

  Isn't it simple? After knowing how to create a DTO, we need to consider how to convert Mo into a dto. Of course, there are still third-party tools that can help us do this. One of the more famous tools is Dozer. The use of Dozer is also simple, in its configuration file to identify the need to convert two types can be:

1 <Mapping> 2     <class-a>Com.ambergarden.egoods.mo.Address</class-a>3     <Class-b>Com.ambergarden.edoods.dto.Address</Class-b>4 </Mapping>

  At run time, Dozer uses reflection to match and assign values to the properties of each of the same names in the two types. If you have properties of different names in two types, then software developers can explicitly specify the properties that match each other:

1 <Mapping> 2     <class-a>Com.ambergarden.egoods.mo.Address</class-a>3     <Class-b>Com.ambergarden.edoods.dto.Address</Class-b>   4     <Field>5         <a>Name</a>6         <b>Owner</b>7     </Field>8 </Mapping>

In addition, Dozer also supports a lot of conversion functions, where we do not introduce each.

With the help of these tools, it has become much easier to add dtos to the system. In the daily maintenance of DTOs, we may need to add some new dtos, or change existing dtos. In this case, we just need to change the file that describes the DTO and update the dozer configuration file. Of course, if custom conversion logic is used in Dozer, then the software developer needs to update the corresponding conversion logic.

anemia of DTO

The DTO contains only data and does not contain any behavior. "I know that," you might say.

But don't be careless. This often causes you to fall into the trap of anemic models. In the business logic implementation of the server side and in the client's page logic, we sometimes need to specify the operational logic for the data. In terms of object-oriented design, some logic should actually be defined in these types. But since the DTO itself does not define these logic, we need to define them outside of these types, such as defining a series of auxiliary functions for these types in a helper class.

One of the simplest examples is the checking of data validity. For example, in a person class, we use an integer data to record the age of the character:

1 class Person {2     Private int Age ; 3     ... 4 }

So in the business logic, we need to check if the domain is set to a negative number. Because DTOs are automatically generated using tools, these check logic cannot be placed in the DTO class. As a workaround, we need to write an auxiliary class to complete the function. But with this growing demand, the management of these ancillary functions will become increasingly difficult. At this point you will be completely trapped in the anemia model trap.

In other words, the main responsibility of a DTO is to transfer data, but it is not good or even suitable for representing a complex concept in business logic. A complex concept is often associated with some reusable complex logic, but that's what DTOs can't do.

In order to solve this problem, we can add a business logic representation on the server, namely, the Bo (Businesses Object). In this case, MO will not be converted directly to a DTO, but to a bo. When all the business is processed and the data needs to be sent to the customer, the Bo is converted to a DTO for transmission.

On the client side, we can also introduce a new layer of data representation that is more appropriate for page logic. This data representation is called a VM (ViewModel), which is the model defined for the sake of the apparent presentation. Sometimes, some class libraries offer simpler methods, such as the mixin features provided by Yui and ExtJS.

Of course, before adding these data representations, software developers need to carefully consider the balance between the amount of work required to add these models and the benefits they bring.

DTO vs. DAO

Some people may be stunned when they see the headline. Yes, there is no comparability of the two. But if a person understands a dto and knows that DAO is an abbreviation for Data Access object, he might naturally think of DAO as a DTO, which is used to represent the type taken from the Dal to represent the data in the database.

In fact, DAO is a standard pattern for organizing database access logic. In other words, it should be a common method for a series of data accesses, such as repository mode. So at the end of this article, we need to emphasize that DAO and Mo are not a concept. Because this article focuses on data, and DAO itself can be used as a separate blog, it will not be described in detail in this article.

Copyright:

Reprint Please specify the original address and marked reprint:http://www.cnblogs.com/loveis715/p/4379656.html

Commercial reprint please contact me in advance:[email protected]

dto– core data in service implementations

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.