DTO: one possible implementation
In the previous post we discussed the problem of Domain Model Pollution with properties that serves the user interface needs. We close the post nominating the DTO’s.
What is a DTO?
A DTO, in this case, is an anemic object (only properties no methods) that serve only one need: trasport information from the application layer to the user interface (and eventually back).
In the example of last post, the solution to the binding problem can be resolved using a DTO in this way:
public class EmployeeDTO : Employee
{
public String FullAddress
{
get { return String.Format("{0}, {1}", Address.Street, Address.City);}
}
}
The object EmployeeDTO use inheritance for having all the properties of the object Employee with the addition of properties FullAddress.
The proposed solution, even if is immediate and simple, is not the best one. The problem is that the object EmployeeDTO inherits from Employee and so it’s have all the public (and protected) properties and methods becoming too rich to be used in a simple manner: the developer can loose the perception that EmployeeDTO is only a data container because he can use all the methods of Employee.
In addition to this problem, there is a second one. Suppose that you need to expose the property Name of the class Employee on the user interface and make the first letter uppercase (only for presentation). In the class EmployeeDTO I should override the property Name, but it isn’t defined virtual in the base class so I can’t do it. Then? The problem of pollution came back: I should mark the property Name as virtual.
A better solution to these problems is in one of the base principle of Object Oriented Development: “Favor encapsulation over inheritance”.
[To be continued....]
1 comment
RSS


