Environment:
Description:
Ok, let's say I have a web application with two domain objects:
a User can have a lot of Reports (one to many relation). Please consider that a Report is a very complex object, with a lot of attributes.
User class:
public class User {
private Set<Report> reports = new HashSet<Report>();
}
Report class:
public class Report {
//...so maaaaaaany attributes
private String name;
}
Let's say I need to show an html page displaying a User profile with the list of associated Reports. Only reports' names appear in the list. Please comment these considerations:
So a possible solution is to modify the User class as follows:
public class User {
private Set<Report> reports = new HashSet<Report>();
private List<String> reportNames;
}
taking the needed information from the report to the user. In my opinion, it brings two consequences:
So is there a nice solution to cope with this problem? I think it is common issue for developers.
One way would be to use the following pattern:
Create a view object which represents exactly what you want to be displayed, let's call it UserViewObject
. I would not modify the domain objects just to adapt them for the view, that would break the MVC design.
Implements a service method in a service class which returns a list of UserViewObject
.
Let the service method call a DAO method in a DAO class that actually does the job.
The DAO method could make sure to only read the required data, or you could do that transformation in the service layer. It is really a bit of what you prefer, and how it fits in. But do not make the DAO layer aware of your UserViewObject
.