====== Value Object ====== ===== Alternative Names ===== ===== Context ===== * [[contexts:Object-Oriented Design]] ===== Intent ===== Represent a concept which is bound to value rather than identity. ===== Problem ===== In many object-oriented languages objects have referential semantics. A variable holding an object does not hold the object itself but rather a pointer, a reference, to it. Assignment copies the reference instead of the object. This behavior is desirable in many cases. You don't want to copy your controller classes when you have several variables for it. A person has an identity. A separate person with the same name is certainly a separate person. So it's quite natural that two objects of type Person are also different. Also changing the person's name doesn't change its identity. But there are classes or concepts which work differently. The Integer 4 is obviously fixed. It doesn't make any sense to change its value. The same holds for the date 2015-06-24, the customer number 12345 or the amount of money denoted by "USD 12.00". Having reference semantics for dates is not very helpful. Two objects which both represent the same customer number are to be considered equal. Twelve dollars are twelve dollars now and will be twelve dollars tomorrow. So there are the "normal" reference kind of objects and the other value-like kind of objects. ===== Solution ===== * Make the value object class immutable. * Provide an implementation for checking equality (''equals'' method, ''=='' operator, etc.) Some languages have built-in concepts for value objects (C#, Delphi, ...). ==== Structure ==== ==== Dynamics ==== ==== Implementation Hints ==== * Typically programming languages demand providing a corresponding ''hashCode'' method when equality is defined differently from identity * Providing a suitable ''toString'' method is often desirable ==== Variations ==== ===== Origin ===== ===== Advantages ===== /*reference principles here*/ * [[principles:Murphy's Law|ML]]: Value objects prevent [[glossary:aliasing]] bugs. * Immutable objects are thread-safe ===== Disadvantages ===== /*reference principles here*/ * [[principles:Generalization Principle|GP]]: Immutable objects cannot change state ===== Relations to Other Patterns ===== ==== Generalizations ==== ==== Specializations ==== * [[Quantity]] * [[Money]] * [[Type-Safe Wrapper]] ==== Alternative Patterns ==== ==== Complementary Patterns ==== * [[Data Transfer Object]] ==== Pattern Collections ==== ===== Examples ===== ==== Example 1: ==== ===== Description Status ===== /* Choose one of the following and comment out the rest: */ [[wiki:Stub]] /*[[wiki:Incomplete]]*/ /*[[wiki:Complete]]*/ ===== Further Reading ===== * Patterns of Enterprise Application Architecture, p. 486 ===== Discussion ===== Discuss this wiki article and the pattern on the corresponding [[talk:patterns:Value Object|talk page]].