Adam Bien's Weblog
How evil are Data Transfer Objects (DTOs)?
DTOs aren't dead. The opposite is true. In certain situations, they become the necessary tool or workaround to solve a particular problem. Impedance mismatch between layers is rather common. The object driven JPA (entity/domain layer) is often kept DRY and fluent, whereby the database driven approach results in anemic domain objects. In either case you would like to keep your exposed REST-API simple and lean. Some relations are probably going to be collapsed, attributes renamed and even types changed. E.g. storing java.util/sql.Dates in a database might be o.k., but it doesn't have to be serialized directly into JSON / XML - sometimes a simple String or int does a better job.
It is perfect valid to introduce a dedicated DTO to adapt an incompatible domain layer. It is much better, than changing the domain layer to the needs of a particular client. Then your domain layer will become dependent on the particular client. ...and in long term this approach will hit the maintainability.
On the other hand considering a dedicated DTO layer as an investment, rarely pays off and often lead to over-engineered and bloated architectures. At the beginning the DTOs will be identical to your domain layer - without any impedance mismatch. If you are "lucky", you will get few differences over the time. Especially with lightweight platforms like Java EE 6, the introduction of a DTO is a bottom-up, rather than top-down approach. Exactly like it is the case with DAOs.
Substantially more important for the maintainability is a single, dedicated, canonical layer. You have to commit your efforts either to the database (or XML-schema etc.) or your domain objects and derive everything from that. In best case even generate all "throw-away" artifacts from your clean, canonical representation.
[see page 153 and 253 in "Real World Java EE Patterns - Rethinking Best Practices" book]
Special Events: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014 and Java EE 7: "Testing and Code Quality", 14th October, 2014 Tweet Follow @AdamBien