Files
java-design-patterns/data-transfer-object/README.md
T
Ilkka Seppälä 6cd2d0353a docs: Content SEO updates (#2990)
* update yaml frontmatter format

* update abstract document

* update abstract factory

* use the new pattern template

* acyclic visitor seo

* adapter seo

* ambassador seo

* acl seo

* aaa seo

* async method invocation seo

* balking seo

* bridge seo

* builder seo

* business delegate and bytecode seo

* caching seo

* callback seo

* chain seo

* update headings

* circuit breaker seo

* client session + collecting parameter seo

* collection pipeline seo

* combinator SEO

* command seo

* cqrs seo

* commander seo

* component seo

* composite seo

* composite entity seo

* composite view seo

* context object seo

* converter seo

* crtp seo

* currying seo

* dao seo

* data bus seo

* data locality seo

* data mapper seo

* dto seo

* decorator seo

* delegation seo

* di seo

* dirty flag seo

* domain model seo

* double buffer seo

* double checked locking seo

* double dispatch seo

* dynamic proxy seo

* event aggregator seo

* event-based asynchronous seo

* eda seo

* event queue seo

* event sourcing seo

* execute around seo

* extension objects seo

* facade seo

* factory seo

* factory kit seo

* factory method seo

* fanout/fanin seo

* feature toggle seo

* filterer seo

* fluent interface seo

* flux seo

* flyweight seo

* front controller seo

* function composition seo

* game loop seo

* gateway seo

* guarded suspension seo

* half-sync/half-async seo

* health check seo

* hexagonal seo

* identity map seo

* intercepting filter seo

* interpreter seo

* iterator seo

* layers seo

* lazy loading seo

* leader election seo

* leader/followers seo

* lockable object seo

* rename and add seo for marker interface

* master-worker seo

* mediator seo

* memento seo

* metadata mapping seo

* microservice aggregator seo

* api gw seo

* microservices log aggregration seo

* mvc seo

* mvi seo

* mvp seo

* mvvm seo

* monad seo

* monitor seo

* monostate seo

* multiton seo

* mute idiom seo

* naked objects & notification seo

* null object seo

* object mother seo

* object pool seo

* observer seo

* optimistic locking seo

* page controller seo

* page object seo

* parameter object seo

* partial response seo

* pipeline seo

* poison pill seo

* presentation model seo

* private class data seo

* producer-consumer seo

* promise seo

* property seo

* prototype seo

* proxy seo

* queue-based load leveling seo

* reactor seo

* registry seo

* repository seo

* RAII seo

* retry seo

* role object seo

* saga seo

* separated interface seo

* serialized entity seo

* serialized lob seo

* servant seo

* server session seo

* service layer seo

* service locator seo

* service to worker seo

* sharding seo

* single table inheritance seo

* singleton seo

* spatial partition seo

* special case seo

* specification seo

* state seo

* step builder seo

* strangler seo

* strategy seo

* subclass sandbox seo

* table module seo

* template method seo

* throttling seo

* tolerant reader seo

* trampoline seo

* transaction script seo

* twin seo

* type object seo

* unit of work seo

* update method seo

* value object seo

* version number seo

* virtual proxy seo

* visitor seo

* seo enhancements

* seo improvements

* SEO enhancements

* SEO improvements

* SEO additions

* SEO improvements

* more SEO improvements

* rename hexagonal + SEO improvements

* SEO improvements

* more SEO stuff

* SEO improvements

* SEO optimizations

* SEO enhancements

* enchance SEO

* improve SEO

* SEO improvements

* update headers
2024-06-08 19:54:44 +03:00

10 KiB

title, shortTitle, description, category, language, tag
title shortTitle description category language tag
Data Transfer Object Pattern in Java: Simplifying Data Exchange Between Subsystems Data Transfer Object (DTO) Learn about the Data Transfer Object (DTO) pattern, its implementation, and practical uses in Java applications. Optimize data transfer between layers with this structural design pattern. Structural en
Client-server
Data transfer
Decoupling
Layered architecture
Optimization

Also known as

  • Transfer Object
  • Value Object

Intent of Data Transfer Object Design Pattern

The Data Transfer Object (DTO) pattern is used to transfer data between software application subsystems or layers, particularly in the context of network calls or database retrieval in Java applications. It reduces the number of method calls by aggregating the data in a single transfer.

Detailed Explanation of Data Transfer Object Pattern with Real-World Examples

Real-world example

Imagine a large company with several departments (e.g., Sales, HR, and IT) needing to share employee information efficiently. Instead of each department querying and retrieving data like name, address, and role individually, they use a courier service to bundle this data into a single package. This package, representing a Data Transfer Object (DTO), allows the departments to easily receive and process comprehensive employee data without making multiple requests. This simplifies data handling, reduces communication overhead, and ensures a standardized format across the company.

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 of DTO Pattern in Java

Let's first introduce our simple CustomerDTO record.

public record CustomerDto(String id, String firstName, String lastName) {}

CustomerResource record acts as the server for customer information.

public record CustomerResource(List<CustomerDto> customers) {

    public void save(CustomerDto customer) {
        customers.add(customer);
    }
    
    public void delete(String customerId) {
        customers.removeIf(customer -> customer.id().equals(customerId));
    }
}

Now fetching customer information is easy since we have the DTOs. The 2nd example uses ProductDTO similarly.

public class App {

  public static void main(String[] args) {

    // Example 1: Customer DTO
    var customerOne = new CustomerDto("1", "Kelly", "Brown");
    var customerTwo = new CustomerDto("2", "Alfonso", "Bass");
    var customers = new ArrayList<>(List.of(customerOne, customerTwo));

    var customerResource = new CustomerResource(customers);

    LOGGER.info("All customers:");
    var allCustomers = customerResource.customers();
    printCustomerDetails(allCustomers);

    LOGGER.info("----------------------------------------------------------");

    LOGGER.info("Deleting customer with id {1}");
    customerResource.delete(customerOne.id());
    allCustomers = customerResource.customers();
    printCustomerDetails(allCustomers);

    LOGGER.info("----------------------------------------------------------");

    LOGGER.info("Adding customer three}");
    var customerThree = new CustomerDto("3", "Lynda", "Blair");
    customerResource.save(customerThree);
    allCustomers = customerResource.customers();
    printCustomerDetails(allCustomers);

    // Example 2: Product DTO

    Product tv = Product.builder().id(1L).name("TV").supplier("Sony").price(1000D).cost(1090D).build();
    Product microwave =
        Product.builder()
            .id(2L)
            .name("microwave")
            .supplier("Delonghi")
            .price(1000D)
            .cost(1090D).build();
    Product refrigerator =
        Product.builder()
            .id(3L)
            .name("refrigerator")
            .supplier("Botsch")
            .price(1000D)
            .cost(1090D).build();
    Product airConditioner =
        Product.builder()
            .id(4L)
            .name("airConditioner")
            .supplier("LG")
            .price(1000D)
            .cost(1090D).build();
    List<Product> products =
        new ArrayList<>(Arrays.asList(tv, microwave, refrigerator, airConditioner));
    ProductResource productResource = new ProductResource(products);

    LOGGER.info(
        "####### List of products including sensitive data just for admins: \n {}",
        Arrays.toString(productResource.getAllProductsForAdmin().toArray()));
    LOGGER.info(
        "####### List of products for customers: \n {}",
        Arrays.toString(productResource.getAllProductsForCustomer().toArray()));

    LOGGER.info("####### Going to save Sony PS5 ...");
    ProductDto.Request.Create createProductRequestDto =
        new ProductDto.Request.Create()
            .setName("PS5")
            .setCost(1000D)
            .setPrice(1220D)
            .setSupplier("Sony");
    productResource.save(createProductRequestDto);
    LOGGER.info(
        "####### List of products after adding PS5: {}",
        Arrays.toString(productResource.products().toArray()));
  }

  private static void printCustomerDetails(List<CustomerDto> allCustomers) {
    allCustomers.forEach(customer -> LOGGER.info(customer.firstName()));
  }
}

The console output:

11:10:51.838 [main] INFO com.iluwatar.datatransfer.App -- All customers:
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Kelly
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Alfonso
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- ----------------------------------------------------------
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Deleting customer with id {1}
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Alfonso
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- ----------------------------------------------------------
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Adding customer three}
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Alfonso
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Lynda
11:10:51.848 [main] INFO com.iluwatar.datatransfer.App -- ####### List of products including sensitive data just for admins: 
 [Private{id=1, name='TV', price=1000.0, cost=1090.0}, Private{id=2, name='microwave', price=1000.0, cost=1090.0}, Private{id=3, name='refrigerator', price=1000.0, cost=1090.0}, Private{id=4, name='airConditioner', price=1000.0, cost=1090.0}]
11:10:51.852 [main] INFO com.iluwatar.datatransfer.App -- ####### List of products for customers: 
 [Public{id=1, name='TV', price=1000.0}, Public{id=2, name='microwave', price=1000.0}, Public{id=3, name='refrigerator', price=1000.0}, Public{id=4, name='airConditioner', price=1000.0}]
11:10:51.852 [main] INFO com.iluwatar.datatransfer.App -- ####### Going to save Sony PS5 ...
11:10:51.856 [main] INFO com.iluwatar.datatransfer.App -- ####### List of products after adding PS5: [Product{id=1, name='TV', price=1000.0, cost=1090.0, supplier='Sony'}, Product{id=2, name='microwave', price=1000.0, cost=1090.0, supplier='Delonghi'}, Product{id=3, name='refrigerator', price=1000.0, cost=1090.0, supplier='Botsch'}, Product{id=4, name='airConditioner', price=1000.0, cost=1090.0, supplier='LG'}, Product{id=5, name='PS5', price=1220.0, cost=1000.0, supplier='Sony'}]

When to Use the Data Transfer Object Pattern in Java

Use the Data Transfer Object pattern when:

  • When you need to optimize network traffic by reducing the number of calls, especially in a client-server architecture.
  • In scenarios where batch processing of data is preferred over individual processing.
  • When working with remote interfaces, to encapsulate the data transfer in a serializable object that can be easily transmitted.

Data Transfer Object Pattern Java Tutorials

Real-World Applications of DTO Pattern in Java

  • Remote Method Invocation (RMI) in Java, where DTOs are used to pass data across network.
  • Enterprise JavaBeans (EJB), particularly when data needs to be transferred from EJBs to clients.
  • Various web service frameworks where DTOs encapsulate request and response data.

Benefits and Trade-offs of Data Transfer Object Pattern

Benefits:

  • Reduces network calls, thereby improving application performance.
  • Decouples the client from the server, leading to more modular and maintainable code.
  • Simplifies data transmission over the network by aggregating data into single objects.

Trade-offs:

  • Introduces additional classes into the application, which may increase complexity.
  • Can lead to redundant data structures that mirror domain models, potentially causing synchronization issues.
  • May encourage design that leads to an anemic domain model, where business logic is separated from data.
  • Composite Entity: DTOs may be used to represent composite entities, particularly in persistence mechanisms.
  • Facade: Similar to DTO, a Facade may aggregate multiple calls into one, improving efficiency.
  • Service Layer: Often involves using DTOs to transfer data across the boundary between the service layer and its clients.

References and Credits