User Tools

Site Tools


patterns:value_object

Value Object

Alternative Names

Context

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

  • ML: Value objects prevent aliasing bugs.
  • Immutable objects are thread-safe

Disadvantages

  • GP: Immutable objects cannot change state

Relations to Other Patterns

Generalizations

Specializations

Alternative Patterns

Complementary Patterns

Pattern Collections

Examples

Example 1:

Description Status

Further Reading

  • Patterns of Enterprise Application Architecture, p. 486

Discussion

Discuss this wiki article and the pattern on the corresponding talk page.

patterns/value_object.txt · Last modified: 2015-06-24 23:18 by christian