Skip to content

Lesson 2 of 9 · 22m

Value Objects and Invariants

The difference between data that merely exists and objects that cannot be wrong: invariants, factories, immutability, and total construction.

The expensive bugs in OO systems are rarely in algorithms. They are invalid objects traveling through valid code: an order with negative quantity, a user whose email was normalized in one path but not another, a date range whose end precedes its start. The cure is not more validation scattered through controllers. The cure is making invalid objects unrepresentable.

Make construction total

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

    @classmethod
    def parse(cls, raw: str) -> "Email":
        normalized = raw.strip().lower()
        local, sep, domain = normalized.partition("@")
        if not sep or not local or "." not in domain:
            raise ValueError(f"invalid email: {raw!r}")
        return cls(normalized)

Email.parse either returns a valid object or raises. Once downstream code receives Email, it no longer checks string shape, whitespace, case, or separator placement. That is the point: validation happens once, at the boundary, and the type communicates proof.

Invariants belong beside the data

@dataclass(frozen=True)
class DateRange:
    start: date
    end: date

    def __post_init__(self) -> None:
        if self.end < self.start:
            raise ValueError("end cannot precede start")

    def contains(self, day: date) -> bool:
        return self.start <= day <= self.end

An invariant is a rule that must always be true. If every path can construct a bad DateRange, then every consumer eventually implements a partial check. Put the rule on the object and consumers can focus on behavior.

A mutable object can be changed after being placed in a set, used as a dict key, shared across tasks, or passed to a cache. The failure appears far away from the mutation. Frozen value objects make equality, hashing, caching, and concurrency boring — boring is what you want in foundational types.

But don't model the universe

The failure mode in the other direction is primitive phobia: twenty classes wrapping strings, none adding a rule. A value object earns its existence when it owns a real invariant, a meaningful operation, or a unit conversion. UserId can be worth it in a large system because mixing user IDs and team IDs is a real incident. FirstName usually is not.

Field notes

  • Prefer factory methods like parse over constructors that both validate and expose raw initialization.
  • Value objects should compare by value, hash consistently, and avoid references to mutable services.
  • Units are invariants too: store cents as integers or meters as floats with the unit in the name or type.
  • If two fields must change together, they probably belong in one object; setters that update half an invariant are how corruption starts.

Was this lesson helpful?

Sign in to rate