Wednesday, September 8, 2010

DTOs can be your domain model

Thanks to the powers of the web I can across this blog post today, To DTO or not to DTO. Reading it made me think about how we model data in our EE systems.

I disagree with Gunther that "You must maintain two separate models: a domain model in the backend that implements the business functionality and a DTO model that transports more or less the same data to the presentation layer." Not necessarily true. Quite often the way you represent the model in Java is a natural representation of the entity and thus can be reused by different layers of the system. Take a Customer for example. The properties of a Customer, their name, address, etc wont change between the DB and the system the Call Center person is using to lookup a customer's profile. So why not have a single model that gets reused?

I think it comes down to two reasons. The first is that we think we need "DTOs" and "Entities" and other EE artifacts. Which is conceptually true, but thinking that way causes us to separate the modeling approach so that we end up with different models. But why not reuse the Java class and morph it into whatever EE thing we need? Use ORM tools to squeeze the object into your relational table structures. Use other tools for transmitting and presenting the model (serialisation into XML via JAXB can do this)

The second is a technological issue. We bind a model to a certain layer limiting it's reuse. This is extremely noticeable through the use of annotations and the way they bind us. Using XML deployment descriptors in the correct layer can help us avoid this technological limitation.

Of course you may need to deviate from a single model, but I would question why first? There may be a legitimate technical need, or poor design decision made by a senior architect. If you do have to have two models, make sure that you don't get bogged down in mapping between the two.