Value Object pattern

The Value Objects are a fundamental building block of Domain-Driven Design1, and they're used to model concepts of our Ubiquitous Language in code.

Ward Cunningham definition

Examples of value objects are things like numbers, dates, monies and strings. Usually, they are small objects which are used quite widely. Their identity is based on their state rather than on their object identity. This way, you can have multiple copies of the same conceptual value object...2

Martin Fowler definition

A small Object such as a Money or the date range object. Their key property is that they follow value semantics rather than reference semantics. You can usually tell them because their notion of equality isn't based on identity, instead two Value Objects are equal if all their fields are equal. Although all fields are equal, you don't need to compare all fields if a subset is unique — for example currency codes for currency objects are enough to test equality. A general heuristic is that Value Objects should be entirely immutable...3

Value Object vs. Entity

Consider the following examples from Wikipedia4, in order to better understand the difference between Value Objects and Entities:

  • Value Object: When people exchange dollar bills, they generally do not distinguish between each unique bill; they only are concerned about the face value of the dollar bill. In this context, dollar bills are Value Objects. However, the Federal Reserve may be concerned about each unique bill; in this context each bill would be an entity.
  • Entity: Most airlines distinguish each seat uniquely on every flight. Each seat is an entity in this context. However, Southwest Airlines, EasyJet and Ryanair do not distinguish between every seat; all seats are the same. In this context, a seat is actually a Value Object.

Value Object Characteristics

While modeling an Ubiquitous Language concept in code, you should always favor Value Objects over Entities. Value Objects are easier to create, test, use, and maintain.

Keeping this in mind, you can determine whether the concept in question can be modeled as a Value Object if:

  • It measures, quantifies, or describes a thing in the Domain
  • It can be kept immutable
  • It models a conceptual whole by composing related attributes as an integral unit
  • It can be compared with others through value equality
  • It is completely replaceable when the measurement or description changes
  • It supplies its collaborators with side-effect-free behavior
1. “Domain-driven Design”, This content
2. “Value Object”, Ward Cunningham, http://wiki.c2.com/?ValueObject
3. “Value Object”, Martin Fowler, https://martinfowler.com/bliki/ValueObject.html
4. “Domain-driven design - Building blocks - Value Object”, Wikipedia, https://en.wikipedia.org/wiki/Domain-driven_design#Building_blocks

results matching ""

    No results matching ""