#590 add explanation for DTO

This commit is contained in:
Ilkka Seppälä 2020-07-18 17:10:50 +03:00
parent 5aacdecc6c
commit 09cee8ffa7
5 changed files with 121 additions and 7 deletions

View File

@ -9,8 +9,89 @@ tags:
--- ---
## Intent ## Intent
Pass data with multiple attributes in one shot from client to server, Pass data with multiple attributes in one shot from client to server, to avoid multiple calls to remote server.
to avoid multiple calls to remote server.
## Explanation
Real world example
> We need to fetch information about customers from remote database. Instead of querying the attributes one at a time, we use DTOs to transfer all the relevant attributes in a single shot.
In plain words
> Using DTO relevant information can be fetched with a single backend query.
Wikipedia says
> In the field of programming a data transfer object (DTO) is an object that carries data between processes. The
motivation for its use is that communication between processes is usually done resorting to remote interfaces
(e.g., web services), where each call is an expensive operation. Because the majority of the cost of each call is
related to the round-trip time between the client and the server, one way of reducing the number of calls is to use an
object (the DTO) that aggregates the data that would have been transferred by the several calls, but that is served by
one call only.
**Programmatic Example**
Let's first introduce our simple customer DTO class.
```java
public class CustomerDto {
private final String id;
private final String firstName;
private final String lastName;
public CustomerDto(String id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public String getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
```
Customer resource class acts as the server for customer information.
```java
public class CustomerResource {
private List<CustomerDto> customers;
public CustomerResource(List<CustomerDto> customers) {
this.customers = customers;
}
public List<CustomerDto> getAllCustomers() {
return customers;
}
public void save(CustomerDto customer) {
customers.add(customer);
}
public void delete(String customerId) {
customers.removeIf(customer -> customer.getId().equals(customerId));
}
}
```
Now fetching customer information is easy since we have the DTOs.
```java
var allCustomers = customerResource.getAllCustomers();
allCustomers.forEach(customer -> LOGGER.info(customer.getFirstName()));
// Kelly
// Alfonso
```
## Class diagram ## Class diagram
![alt text](./etc/data-transfer-object.urm.png "data-transfer-object") ![alt text](./etc/data-transfer-object.urm.png "data-transfer-object")

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<class-diagram version="1.2.0" icons="true" always-add-relationships="false" generalizations="true" realizations="true" <class-diagram version="1.2.0" icons="true" always-add-relationships="false" generalizations="true" realizations="true"
associations="true" dependencies="false" nesting-relationships="true" router="FAN"> associations="true" dependencies="false" nesting-relationships="true" router="FAN">
<class id="1" language="java" name="com.iluwatar.datatransfer.CustomerClientApp" project="data-transfer-object" <class id="1" language="java" name="com.iluwatar.datatransfer.App" project="data-transfer-object"
file="/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerClientApp.java" binary="false" file="/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerClientApp.java" binary="false"
corner="BOTTOM_RIGHT"> corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="145" y="93"/> <position height="-1" width="-1" x="145" y="93"/>

View File

@ -48,7 +48,7 @@
<configuration> <configuration>
<archive> <archive>
<manifest> <manifest>
<mainClass>com.iluwatar.datatransfer.CustomerClientApp</mainClass> <mainClass>com.iluwatar.datatransfer.App</mainClass>
</manifest> </manifest>
</archive> </archive>
</configuration> </configuration>

View File

@ -32,15 +32,15 @@ import org.slf4j.LoggerFactory;
* The Data Transfer Object pattern is a design pattern in which an data transfer object is used to * The Data Transfer Object pattern is a design pattern in which an data transfer object is used to
* serve related information together to avoid multiple call for each piece of information. * serve related information together to avoid multiple call for each piece of information.
* *
* <p>In this example, ({@link CustomerClientApp}) as as customer details consumer i.e. client to * <p>In this example, ({@link App}) as as customer details consumer i.e. client to
* request for customer details to server. * request for customer details to server.
* *
* <p>CustomerResource ({@link CustomerResource}) act as server to serve customer information. And * <p>CustomerResource ({@link CustomerResource}) act as server to serve customer information. And
* The CustomerDto ({@link CustomerDto} is data transfer object to share customer information. * The CustomerDto ({@link CustomerDto} is data transfer object to share customer information.
*/ */
public class CustomerClientApp { public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomerClientApp.class); private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/** /**
* Method as act client and request to server for details. * Method as act client and request to server for details.

View File

@ -0,0 +1,33 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.datatransfer;
import org.junit.jupiter.api.Test;
public class AppTest {
@Test
public void test() throws Exception {
App.main(new String[]{});
}
}