Value Object

Value Object

A value object is a domain object defined entirely by its data. Two value objects with the same fields are the same value. No identity, no lifecycle, immutable.

Defining trait

Python shape

from dataclasses import dataclass
import re

@dataclass(frozen=True)
class Email:
    value: str

    def __post_init__(self):
        if not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", self.value):
            raise ValueError(f"invalid email: {self.value!r}")

    def domain(self) -> str:
        return self.value.split("@", 1)[1]

frozen=True gives free __eq__ + __hash__ over all fields. __post_init__ enforces validity at construction. Methods are derived — they don't change the VO, they compute from it.

Examples

Concept Why a VO
Money(amount, currency) Identity meaningless; currency-aware equality + arithmetic
ISBN(value) Self-validating, normalised, immutable
DateRange(start, end) start <= end invariant, can compute overlap
Address(street, city, zip) Two addresses with same fields ARE the same address
Coordinates(lat, lon) Pure data, used for distance, intersection

Anti-patterns

VO vs Entity

VO Entity
Identity None Required
Equality All fields ID only
Mutation Replace In-place via methods
Storage Often inline (column / JSON) Own table + ID

Three rules of thumb

  1. If two instances with the same fields are "the same thing" -> VO.
  2. If you'd never update a field in place -> VO.
  3. If construction must validate -> VO with __post_init__.

Why bother

Every primitive replaced by a VO is a class of bugs you cannot write. transfer(amount: Money) cannot be called with transfer(100, "currency") swapped. def send(to: Email) cannot accept a garbled string. The compiler/type-checker becomes a domain validator.