I'd like to use DTO's in my view models in lieu of my domain objects, however I'm having a hard time justifying the maintenance overhead of having to maintain two sets of properties for each domain object.
I was wondering if anyone has implemented or knows of a pattern where the properties of a domain object are separated from the object's actions without having to maintain two sets of properties.
One thought I had would be to have my domain object be only properties and attaching the actions as a subclass:
public class Person{
private String firstName;
private String lastName;
public String getFirstName(){
return this.firstName;
}
public String setFirstName(string firstName){
this.firstName = firstName;
}
...
}
public class PersonActions extends Person{
public void save(){
...
}
public Person get(){
}
}
This way still feels a bit kludgy as I'd have to pass around a PersonAction class if I wanted a full representation of the domain object.
Difference between DTO & Entity: Entity is class mapped to table. Dto is class mapped to "view" layer mostly. What needed to store is entity & which needed to 'show' on web page is DTO.
A DTO is helpful whenever you need to group values in ad hoc structures for passing data around. From a pure design perspective, DTOs are a solution really close to perfection. DTOs help to further decouple presentation from the service layer and the domain model.
DTOs are called Data Transfer Objects because their whole purpose is to shift data in expensive remote calls. They are part of implementing a coarse grained interface which a remote interface needs for performance.
Data Transfer Objects (DTOs) and View Models (VMs) are not the same concept! The main difference is that while VMs can encapsulate behaviour, DTOs do not. The purpose of a DTO is the transfer of data from one part of an application to another.
You could use an interface exposing only your object's data, without any domain methods. You'd still need to maintain two classes, but that would be a lot easier since most of the changes could be refactored by your IDE (Eclipse for example). Here's an example:
public interface PersonView {
String getFirstName();
String setFirstName();
}
public void Person implements PersonView {
private String firstName;
@Override // This annotation guarantees the interface is correct
public String getFirstName() {
return firstName;
}
...domain methods...
}
Is not a perfect solution, but it's a pretty clean one.
As for the problem itself, I for one don't really mind exposing the whole object to the view layer. IMHO, I don't think hiding some methods is worth the overhead. The team should have the discipline to use the objects wisely, but that's just my opinion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With