Sunday, June 19, 2011

Design Pattern: Value Objects (VOs) V.S Data Transfer Object(DTO).


The pattern which is known today as Data Transfer Object was mistakenly (see this definition) called Value Object in the first version of the Core J2EE Patterns. The name was corrected in the second edition of the Core J2EE Patterns book, but the name "Value Object" became very popular and is still used as an alias for the actual DTOs. There is, however, a real difference between both patterns:
  1. Data Transfer Object (DTO) is just as stupid data container which is used to transport data between layers and tiers. It mainly contains of attributes. Actually you can even use public attributes without any getters / setters, but this will probably cause too much meetings and discussions :-). DTOs are anemic in general and do not contain any business logic. DTOs are often java.io.Serializable - its only needed if you are going to transfer the data across JVMs.
  2. A Value Object [1,2] represents itself a fix set of data and is similar to a Java enum. A Value Object doesn't have any identity, it is entirely identified by its value and is immutable. A real world example would be Color.RED, Color.BLUE, SEX.FEMALE etc.
Data Transfer Objects are widely overused and the "real" Value Objects a bit unattended. Most developers who use the term Value Object actually have in mind DTOs. I have to continuously correct myself as well :-).

No comments :

Post a Comment