Table of Contents
Represent a concept which is bound to value rather than identity.
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.
- Make the value object class immutable.
- Provide an implementation for checking equality (
Some languages have built-in concepts for value objects (C#, Delphi, …).
- Typically programming languages demand providing a corresponding
hashCodemethod when equality is defined differently from identity
- Providing a suitable
toStringmethod is often desirable
- GP: Immutable objects cannot change state
Relations to Other Patterns
- Patterns of Enterprise Application Architecture, p. 486
Discuss this wiki article and the pattern on the corresponding talk page.