As my project demands me to learn Enterprise Java for a project on "SaaS (software as a service)", quite far from the Ruby or Rails, I happened to come across a pattern called "Data Transfer Object" or just "DTO".
Its but obvious that, in a decent remote app, we tend to make many remote method invocations. Say for example, for a particular employee, you want to getFirstName(), getLastName(), getAge(), getSalary() blah blah blah... many such calls act as network overhead and unnecessarily slows down the app waiting for the reply.
To solve this problem, DTO pattern is implemented. Here, when a client asks for a particular detail say firstName, he is not only sent that data, but also related info like lastName, age, salary etc through a serialized plain java object. The client grabs the object and keeps fetching required info from that object.
In the following figure(courtesy) , Album artist and singer, 2 different classes on the server side are clubbed together and sent to the client.
Now, lets take a look at the implementation of this pattern. I implemented this in Java using EJB(entity bean).
Entity bean code(server side)
@Entity
public class EmployeeEntity implements Serializable {
private Long id;
private String firstName;
private String lastName;
.
.
.
//constructors go here
//setters and getters of the instances go here
//Below a DTO object is returned. 'TransferObject' is a simple serializable java object
public TransferObject getTransferObject() {
TransferObject to = new TransferObject();
to.setFirstName(this.firstName);
to.setLastName(this.lastName);
.
.
.
return to;
}
}
DTO class code(server side)
public class TransferObject implements java.io.Serializable {
private Long id;
private String firstName;
.
.
.
//Accessors/getters for the above instance variables as per the requirement should go here
}
Thats about it. Client receives the 'TransferObject' object and invokes getters on this object, just like any other java object. All the invocation so made are completely local.
I can't help but quote Martin Fowler in the end, Chief Scientist, ThoughtWorks.
"Patterns always have two parts: the how and the when. Not just do you need to know how to implement them, you also have to know when to use them and when to leave them alone."
DTO pattern
Subscribe to:
Post Comments (Atom)

1 comments:
thanks lot.. very good informative article
Post a Comment