This thought came into my mind when I was returning home from work. It all started with this old dilemma – how should I transform my domain objects into DTO? Maybe I should use a tool, like AutoMapper? Or maybe DTOs should build themselves from domain objects? Maybe DTO assembler pattern is the way to go? There are many possibilities and all of them are answers to my question. And also all of them are correct. Only the question is wrong. How could I be so blinded?

I should ask myself a different question: How would I design my system so that:

  1. business rules are implemented by a domain model,
  2. the domain model is accessed only via application service layer,
  3. GUI allows users to search and view properties of domain objects
  4. there is no unnecessary code duplication

As you see, there is nothing about DTO in the question. That’s because DTO is one of the solutions to this fundamental issue. And the question I started with (‘how do I transform entities to DTOs’) is merely a follow-up question if I choose to use DTOs. So lets return to the right question. How would I design that kind of system?

The answer is very simple: I would use command and query separation. It becomes obvious when you form the question that way. Points 2 and 3 are separate requirements in the specification. Why should I mix them and try to solve these two problems with one piece of code? And here comes the fourth point: doesn’t the CQS solution cause code duplication? It requires me to have two classes for each domain object. That is right, but that is also the requirement of DTO pattern. CQS requires also a duplicate object/relational mapping. That’s the place where DTOs seem to be better. But really, are they?

The answer is: no, they are not. It came to me when I was thinking about AutoMapper. Isn’t it called object/object mapping tool? So it requires a mapping configuration, right? Same as CQS, only in a different form. But what about simple DTO transformation or assembler pattern? They are also an implementation of mapping logic, only done in imperative style.

To sum up: both CSQ and DTO need a set of additional classes and both need a mapping specification per class. The cost is the same, but the benefits of having CQS is far greater than DTO. In fact there is no benefit of having DTOs at all. They simply solve the problem. CQS, on the other hand, gives you also scalability and flexibility in building UI – you can’t overestimate the value of them to your project.

VN:F [1.9.13_1145]
Rating: 4.0/5 (1 vote cast)
Is DTO an excuse?, 4.0 out of 5 based on 1 rating