Browser docs

Data Transfer Object


Pass data with multiple attributes in one shot from client to server, to avoid multiple calls to remote server.


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 CustomerDTO class.

 1public class CustomerDto {
 2  private final String id;
 3  private final String firstName;
 4  private final String lastName;
 6  public CustomerDto(String id, String firstName, String lastName) {
 7 = id;
 8    this.firstName = firstName;
 9    this.lastName = lastName;
10  }
12  public String getId() {
13    return id;
14  }
16  public String getFirstName() {
17    return firstName;
18  }
20  public String getLastName() {
21    return lastName;
22  }

CustomerResource class acts as the server for customer information.

 1public class CustomerResource {
 2  private final List<CustomerDto> customers;
 4  public CustomerResource(List<CustomerDto> customers) {
 5    this.customers = customers;
 6  }
 8  public List<CustomerDto> getAllCustomers() {
 9    return customers;
10  }
12  public void save(CustomerDto customer) {
13    customers.add(customer);
14  }
16  public void delete(String customerId) {
17    customers.removeIf(customer -> customer.getId().equals(customerId));
18  }

Now fetching customer information is easy since we have the DTOs.

1    var allCustomers = customerResource.getAllCustomers();
2    allCustomers.forEach(customer ->;
3    // Kelly
4    // Alfonso

Class diagram

alt text


Use the Data Transfer Object pattern when:

  • The client is asking for multiple information. And the information is related.
  • When you want to boost the performance to get resources.
  • You want reduced number of remote calls.