DTOs Simplify Complex Screens
Jean-Paul is a big fan of DTOs. Initially I was skeptical of because I saw them as an unnecessary additional mapping layer. However I filed this technique away in my tool box. And today I needed to reach into that tool box and DTOs were perfect for the problem in hand.
I was working on a complex screen that was an aggregation of many domain objects. To make matters worse the relevant parts of the domain model were in the middle of a “transitional period”. I wanted to avoid mapping a complex web of properties in the view because of testability concerns. I know that I could use MVP but I don’t think that it adds a lot of value, especially considering the additional effort. Hopefully I am never going to need to use it again because Microsoft MVC will CTP soon.
My solution was to create a DTO and build the screen on that. Initially in the Repository I simply created a stub implementation that returns a hard coded IList<> of the DTOs. Once the screen was working I fixed the domain model.
Previously I posted about NHibernate Projections. With DTOs you need to map from your domain onto the DTO at some point. I chose to do this in the Repository using projection because it is the most efficient place to do this (testing is a little harder than in a mapping layer but not significantly so).
In the process I learned something new about HQL. In some cases we need to use field rather than property (the default) access in the hbm.xml files.When performing the projection I needed to reference the field in the HQL query e.g. “select new CustomerDTO(c.Property, c._field) from Customer c”.


