Thursday, December 1, 2011

Data transfer object or Value Object Design Pattern

DTO stands for Data transfer object or Value Object (VO) design pattern is a one of the design pattern used for transferring the data between one different machine.
The problem:-
In most of the java projects, we have to retrieve the data from the database. In a system, you are queried (select employee id, employee name from employee) in the databases from your application. Here application is either a web application or standalone application (applet or Eclipse RCP client). Assume that the application is executed in Host-1 and MySQL database is hosted in the host-2 box. Whenever you are getting the employee information from the application, application queried the employee id for the first time and employee name for the second time and so on repeats this process for all the records.
Solution:-
here advantages to the database is a network or remote call which is expensive from the application point of view.
The advantages of this approach:-
  • To reduce the network traffic, we will create a java object which has member variables holding each row data and returns each object or list of objects.
  • Data transfer is made easy and network traffic is reduced.
  • Reduce code duplication with this approach
public class Employee {

 private long mEmployeeId;
 private String mEmployeeName;

 public void setEmployeeId(long pEmployeeId) {
  this.mEmployeeId = pEmployeeId;
 }

 public long getEmployeeId() {
  return this.mEmployeeId;
 }

 public void setEmployeeName(String pEmployeeName) {
  this.mEmployeeName = pEmployeeName;
 }

 public String getEmployeeName() {
  return this.mEmployeeName;

 }
}
I forgot to one more point, whenever java object is transferred between different JVM's or machines, that must be serializable. How to make the java object serializable.
for any java object to make serializable, we have to implement java.io.Serializable interface, which has no methods to implement. we can also call this type of interfaces are marker interfaces. so how do we achieve serializable without implementing methods?
JVM assumes that whenever objects are implemented with serializable interfaces. it is eligible for the serialization process. JVM checks each object for using the method (object instanceOf Serializable) for the process.
}

Related article