adam bien's blog

DTO: The Exceptions From The Rule 📎

Most JavaEE applications do not need a Data Transfer Object at all. Built-in support for JSON and XML does the transport job already. However, DTOs are still useful for special case handling like:

  1. Transferring a custom subset, superset (multiple entities) of entity data at once
  2. Dedicated optimizations like sophisticated JAXB mapping, customization of binary transfer e.g. hooks in http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html
  3. Role-dependent dataset: specific roles are only allowed to see specific data attributes. However, a http://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html would solve such a job perfectly as well.
  4. Client-dependent view: native clients may request a different view to data as it can be provided by stock entities. Client may require a DTO per view independently of the organization on the server.
  5. Client technology may expect different contents e.g. a JavaFX client may expect a http://docs.oracle.com/javafx/2/api/javafx/beans/property/StringProperty.html instead of a plain String.

DTOs do not have to be justified in all the use cases above. The reason for introduction is obvious: a DTO is significantly different to the persistent domain object, or the technology forces you to introduce a DTO.

[See also an in-depth discussion in the "Real World Java EE Patterns--Rethinking Best Practices" book (Second Iteration, "Green Book"), page 273 in, chapter "Data Transfer Object", particularly the strategies "Generic DTO", "Client-specific DTO"]

See you at Java EE Workshops at MUC Airport or on demand and in a location very near you: airhacks.io!