Sunday, September 2, 2007

Value Object, Entity and Data Transfer Object

There are several type of object on Object Oriented Programming. There are a lot of misconception of those. Below is some explaination of some type such as Value Object, Entity and Value Object.

What is Value Object?

Value Object is not Entity. According to Martin Fowler http://www.martinfowler.com/ap2/valueObject.html "An object whose conceptual identity is based on a combination of values of its properties." So what was that? It's like Integer, Date, etc. When you want to do an equality those object to another it should compare all it's meaning properties.


public class Grade {
private Subject subject;
private float gradeValue;
....
public boolean equals(Object o) {
...
Grade other = (Grade)o;
// compare all the meaning objects
return subject.equals(subject) && gradeValue == other.gradeValue;
...
}
}

It might have more than one instance of Grade in memory. John has Grade and Brad has it too, we can check the equality by it's properties (subject and the gradeValue). They both might have the same grade.
Address class can be another good example. Lets say that a store have a lot of customers. Addess is composite of city, street, and floor. When we find some customers life on same place we might say they are on the same city, street and floor.

So what is Entity?

Entity might be POJO and Value Object "might" too. It recognized by their identity.

public class User {
private String username;
private String password;
private Group group;
....
public boolean equals(Object o) {
...
User other = (User)o;
return username.equals(other.username);
...
}
}


We only concern to username property as identity and ignore the other properties of User class (password, group). We can imagine entity is like a record on database table which has primary key.

So what is Data Transfer Object?

According to Martin Fowler http://www.martinfowler.com/eaaCatalog/dataTransferObject.html, DTO is "An object that carries data between processes in order to reduce the number of method calls.". The main idea is object that transfered in order to reduce method calls over the network. We can call it as Value Object or we can call it as Entity. When it does? It depends on how we compare the object - Value Object if based on it's properties or Entity if based on it's identity.

references:

No comments: