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
- Equality by value, not by reference.
- Immutable — to "change" a VO is to replace it.
- Self-validating — invalid values cannot exist.
- Composable — combining VOs yields VOs.
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
- Primitive obsession.
strfor email,intfor money cents,tuple[float, float]for coordinates. Loses invariants and self-documentation. Replace with VOs. - Mutable VO. Adding a setter to
Money.amount. Equality, hashing, sharing across collections all break. - VO without validation. A
Emailthat accepts"not-an-email". Use__post_init__to reject invalid construction up front (Fail-Fast). - Storing identity. Giving
Addressanid. If you're tempted, it's actually an entity.
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
- If two instances with the same fields are "the same thing" -> VO.
- If you'd never update a field in place -> VO.
- 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.