I'm wondering what is a clean solution for representing an entity in many different format. Let's suppose I have the following entity:
Person {
Long id;
String title;
String firstName;
String lastName;
Date birthDate;
List contacts;
Address address;
...
Date joinDate;
Date lastLoginDate;
Status status;
}
And I have a web application where I need to display different data from the Person
entity depending on where it is needed. For example:
- Public GUI header: firstName, city(from address), email(from contacts)
- Public GUI profile: title, firsName, lastName, birthDate, contacts, address
- Admin persons list: id, fullName, birthDate, joinDate, lastLoginDate, status
- Admin person edit: all the fields
- REST API: id, title, firstName, lastName, age(as int and not birthDate), address
- Report: id, fullName, fullAddress, birthDate, login attempts (not part of the main entity, get from other service), audit logs (not part of the main entity, get from other service)
In general we know the person's id and can get the entity like personRepository.getById()
I can just send the Person
entity to the various representation layers and get what it needs, but in this case I have to repeat formatting like fullName concatenation, I can accidentally expose data in case of the REST API, in case of list pages it can cause performance degradation, and so on.
Or, I can create unique representation for each case so in this example:
- PersonPublicHeaderViewData
- PersonPublicProfileViewData
- PersonAdminListViewData
- PersonAdminEditViewData
- PersonRestViewData
- PersonReportViewData
In this case I also need some factories that can build the views from the original entity:
- PersonPublicViewFactory: creates header and profile views
- PersonAdminViewFactory: creates admin list and edit views
- PersonRestViewFactory: creates the REST view
- PersonReportViewFactory: create the report view with the additional external data
The second solution seems to be cleaner but requires a lot of extra classes.
What do you think? Any other idea?