Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 1

Entities, value objects and making illegal states unrepresentable

Decide when a domain concept needs an identity and when it is only a value, build immutable value objects that check themselves when they are created, and shape types so that some wrong states cannot even be written.

Contentsand lesson path

What you will learn

  • Distinguish entities from value objects and implement immutable, self-validating value objects.

01. Why it matters

Larkfield Works is a fictional coworking space with twelve meeting rooms, and this skill follows it from lesson to lesson. Its first booking system stored each booking as one flat record: start and end as text, a status word, and optional fields for a door code and a cancellation reason. After a year, support kept a list of records that made no sense: a booking from 14:00 to 13:00, a cancelled booking with no reason, a confirmed booking with no door code. The database had accepted all of them.

These are not typing slips. Each is a state that the model allowed. This lesson covers the first tools of tactical Domain-Driven Design (DDD), the patterns you use inside one bounded context (the boundary from strategic DDD): entities, which keep an identity while their data changes, and value objects, which are defined by their values and check themselves when created. Then you will make some wrong states impossible to write, and weigh the cost.

02. Entities: the same thing through change

A member books room R2 for 09:00, moves it to 14:00, then changes it from four people to six. The door system, the invoice and the member's calendar still mean the same booking: its attributes changed, its identity did not. Eric Evans's DDD Reference describes an entity as an object with 'a thread of continuity and identity' through its lifecycle, and adds that the model must define what it means to be the same thing.

The reverse matters too. A team lead books R2 and R3 for the same hour and headcount because the team splits into two groups. The two bookings carry identical data, yet cancelling one must not cancel the other. So an entity is compared by its identifier, not its fields. The identifier may come from outside (a number on a paper form) or be generated (a UUID, a database sequence); it must never change and never be reused. In Python, switch off the generated field-by-field equality (eq=False) and compare identifiers yourself, as Booking does at the end of the file below.

03. Value objects: described by their values

Now look at the time range 09:00 to 10:30. Nobody asks which 09:00 to 10:30 they mean: any two ranges with the same start and end are interchangeable. Money works the same way: twelve pounds is twelve pounds whichever object holds it, as long as the currency matches. Evans calls these value objects: they describe or compute some characteristic of a thing, have no identity, and are treated as immutable. Martin Fowler explains why immutability matters: if two parts of a program share one mutable object and one changes it, the other sees the change too, an aliasing bug.

A good value object does three things:

  • It is equal by value, so it works as a dictionary key or a set member.
  • It cannot be changed. A different range is a new object, so a range shared by two bookings never shifts under either of them.
  • It checks itself when it is created. If the constructor refuses a backwards range, every TimeRange in the program is valid and the rule lives in one place.

The code needs Python 3.11 or newer and no packages; outputs come from Python 3.12.13. Save both files in one folder.

Python · values.py
"""Value objects and one entity for Larkfield Works meeting rooms."""
from dataclasses import dataclass
from datetime import time


@dataclass(frozen=True)
class TimeRange:
    """A half-open range [start, end) inside one day, on 15-minute marks."""

    start: time
    end: time

    def __post_init__(self) -> None:
        for moment in (self.start, self.end):
            if moment.minute % 15 or moment.second or moment.microsecond:
                raise ValueError(f"{moment:%H:%M:%S} is not on a 15-minute mark")
        if self.start >= self.end:
            raise ValueError(f"{self} is empty or backwards")

    @property
    def minutes(self) -> int:
        start = self.start.hour * 60 + self.start.minute
        return self.end.hour * 60 + self.end.minute - start

    def overlaps(self, other: "TimeRange") -> bool:
        return self.start < other.end and other.start < self.end

    def __str__(self) -> str:
        return f"{self.start:%H:%M}-{self.end:%H:%M}"


@dataclass(frozen=True)
class Money:
    """An amount in minor units (pence, cents) with an ISO 4217 currency code."""

    amount: int
    currency: str

    def __post_init__(self) -> None:
        if self.amount < 0:
            raise ValueError("an amount cannot be negative")
        code = self.currency
        if len(code) != 3 or not code.isalpha() or not code.isupper():
            raise ValueError(f"{self.currency!r} is not a currency code")

    def add(self, other: "Money") -> "Money":
        if other.currency != self.currency:
            raise ValueError(f"cannot add {other.currency} to {self.currency}")
        return Money(self.amount + other.amount, self.currency)


@dataclass(eq=False)
class Booking:
    """An entity: still the same booking after its time or headcount changes."""

    booking_id: str
    member_id: str
    time_range: TimeRange
    headcount: int

    def __eq__(self, other: object) -> bool:
        return isinstance(other, Booking) and other.booking_id == self.booking_id

    def __hash__(self) -> int:
        return hash(self.booking_id)

    def move_to(self, new_range: TimeRange) -> None:
        self.time_range = new_range
Python · try_values.py
"""Equality, immutability and validation of the objects in values.py."""
from dataclasses import FrozenInstanceError, replace
from datetime import time

from values import Booking, Money, TimeRange

morning = TimeRange(time(9, 0), time(10, 30))
same = TimeRange(time(9, 0), time(10, 30))
print("equal:", morning == same, "| same object:", morning is same)
print("distinct values in a set:", len({morning, same}))

try:
    morning.end = time(11, 0)
except FrozenInstanceError as error:
    print("cannot change a value:", error)

longer = replace(morning, end=time(11, 0))
print("replace() builds a new value:", morning, "->", longer)

for start, end in [(time(10, 0), time(9, 0)), (time(9, 10), time(10, 0))]:
    try:
        TimeRange(start, end)
    except ValueError as error:
        print("rejected:", error)

print("fee:", Money(1200, "GBP").add(Money(450, "GBP")))

first = Booking("BK-1", "M-7", morning, headcount=4)
twin = Booking("BK-2", "M-7", morning, headcount=4)
print("same attributes, different bookings:", first == twin)

reloaded = Booking("BK-1", "M-7", TimeRange(time(14, 0), time(15, 0)), headcount=6)
print("different attributes, same booking:", first == reloaded)
Terminal
python3 try_values.py
Expected output
equal: True | same object: False
distinct values in a set: 1
cannot change a value: cannot assign to field 'end'
replace() builds a new value: 09:00-10:30 -> 09:00-11:00
rejected: 10:00-09:00 is empty or backwards
rejected: 09:10:00 is not on a 15-minute mark
fee: Money(amount=1650, currency='GBP')
same attributes, different bookings: False
different attributes, same booking: True

The two ranges are equal although they are different objects, so the set keeps one. Assigning to a field raises FrozenInstanceError. dataclasses.replace() is how you 'change' a value: it builds a new object through the constructor, so __post_init__ checks it like any other. The bad ranges never exist, and Money.add refuses to mix currencies. Two bookings with the same fields differ, while a booking reloaded with new fields is the same one, because Booking compares identifiers.

Two limits of Python matter. Its documentation says it is not possible to create truly immutable Python objects: frozen=True emulates immutability, and object.__setattr__ can get round it. And freezing is shallow: it stops you putting a new object into a field, not changing an object already there, so prefer tuples and other unchangeable types inside value objects.

04. Making illegal states unrepresentable

Value objects stop bad values, not bad combinations. Larkfield's flat record allowed any status with any mix of optional fields, so every screen had to check which fields were really there.

The slogan for the fix is make illegal states unrepresentable, a heading in Yaron Minsky's post Effective ML Revisited on the Jane Street blog (March 2011), which shares code from an OCaml talk he gave to Harvard students. Shape the types so that a nonsensical combination cannot be written, instead of hunting for it later. In TypeScript the tool is a discriminated union: object types that share one literal field, here kind, which tells the compiler which variant it holds. Each state carries only its own data.

TypeScript · booking_state.ts
// Booking states as a discriminated union: each state carries only its own data.
type BookingId = string & { readonly brand: 'BookingId' };
type MemberId = string & { readonly brand: 'MemberId' };

type Requested = { kind: 'requested'; holdUntil: string };
type Confirmed = { kind: 'confirmed'; doorCode: string };
type Cancelled = { kind: 'cancelled'; reason: string };
type BookingState = Requested | Confirmed | Cancelled;

type Booking = { id: BookingId; member: MemberId; state: BookingState };

const bookingId = (raw: string): BookingId => raw as BookingId;
const memberId = (raw: string): MemberId => raw as MemberId;

function describe(booking: Booking): string {
  const state = booking.state;
  switch (state.kind) {
    case 'requested':
      return `${booking.id}: held until ${state.holdUntil}`;
    case 'confirmed':
      return `${booking.id}: confirmed, door code ${state.doorCode}`;
    case 'cancelled':
      return `${booking.id}: cancelled (${state.reason})`;
    default: {
      const unhandled: never = state;
      return unhandled;
    }
  }
}

const newBooking = (id: string, member: string, state: BookingState): Booking => ({
  id: bookingId(id),
  member: memberId(member),
  state,
});

const bookings: Booking[] = [
  newBooking('BK-1', 'M-7', { kind: 'requested', holdUntil: '12:00' }),
  newBooking('BK-2', 'M-7', { kind: 'confirmed', doorCode: '4417' }),
  newBooking('BK-3', 'M-9', { kind: 'cancelled', reason: 'no-show' }),
];
for (const booking of bookings) console.log(describe(booking));

BookingId and MemberId are branded types. TypeScript compares types by structure, not name, so two plain aliases for string would be interchangeable; the fake brand property keeps them apart. This is a community pattern, not a language feature, and the compiler trusts the as casts blindly, so keep them in one place and validate there. The default branch assigns the state to never, a type with no values, so it compiles only while every variant is handled.

Node 22.18 and later run a .ts file by stripping the types, with no type checking, so the compiler is a separate step. Outputs come from Node 22.23.2 and TypeScript 7.0.2, which npx downloads on first use.

Terminal
node booking_state.ts
Expected output
BK-1: held until 12:00
BK-2: confirmed, door code 4417
BK-3: cancelled (no-show)
Terminal
npx --yes -p [email protected] tsc --noEmit --strict booking_state.ts \
  && echo no type errors
Expected output
no type errors

Now paste three typical mistakes at the end of the file and check again. The fold command only wraps the long error lines at 80 characters.

TypeScript · append to booking_state.ts
// Three mistakes that the compiler should refuse.
const cancelledSilently: BookingState = { kind: 'cancelled' };

function doorCodeOf(state: Requested): string {
  return state.doorCode;
}

function findBooking(id: BookingId): string {
  return id;
}
findBooking(memberId('M-7'));
Terminal
npx --yes -p [email protected] tsc --noEmit --strict booking_state.ts \
  | fold -s -w 80
Expected output
booking_state.ts(44,7): error TS2322: Type '{ kind: "cancelled"; }' is not 
assignable to type 'BookingState'.
  Property 'reason' is missing in type '{ kind: "cancelled"; }' but required in 
type 'Cancelled'.
booking_state.ts(47,16): error TS2339: Property 'doorCode' does not exist on 
type 'Requested'.
booking_state.ts(53,13): error TS2345: Argument of type 'MemberId' is not 
assignable to parameter of type 'BookingId'.
  Type 'MemberId' is not assignable to type '{ readonly brand: "BookingId"; }'.
    Types of property 'brand' are incompatible.
      Type '"MemberId"' is not assignable to type '"BookingId"'.

A cancelled booking without a reason does not match Cancelled, a requested booking has no door code, and a member id cannot stand in for a booking id. Node would still run the file, because it never looks at types; in a real project the compiler runs in the editor and in continuous integration, so the mistakes stop there.

What if Larkfield adds a fourth variant, { kind: 'noShow' }, and nobody updates describe? The default branch would receive a real no-show, which cannot be assigned to never, so the compiler names the function that forgot the new state.

Types only protect values the program builds itself, so parse JSON, form fields and database rows into these types at the edge of the system. Python type hints are not checked at run time, so there __post_init__ is what protects you.

05. When a plain record is enough

Value objects are not free. Each is another class to name, test, store and convert, and object-relational mappers need extra setup to embed one in an entity's table. Wrapping every string makes a model harder to read, not easier.

Ask what travels with the value. Wrap it when a rule travels with it (a format, a unit, a currency, a range that must not run backwards) or when mixing it up with a similar value would be a real bug (a member id passed as a booking id, pence passed as pounds). Keep a plain field when nothing checks it and nothing depends on its meaning: a free-text note, or a CSV row that is only passed on. A screen that only creates, edits and lists records is usually best served by plain records; the design patterns lesson on domain logic compares those simpler styles.

Entity or value also depends on the bounded context, not the thing. Fowler's example is a postal address: a simple value in most systems, but a mapping system that links addresses into a hierarchy may track each one by identity. When unsure, ask the domain experts: if two of these had exactly the same data, would you ever need to tell them apart? Giving everything an identity just in case has a cost; Evans notes that it adds analysis work and muddles the model.

06. Check your understanding

Python · equipment.py (predict before you run it)
from dataclasses import dataclass


@dataclass(frozen=True)
class Equipment:
    items: list[str]


kit = Equipment(["screen"])
kit.items.append("camera")
print(kit.items)
Practice check · 3 questions

Entities, values and illegal states

Each question has one best answer. Question 1 uses equipment.py above.

Q1. A teammate writes equipment.py, shown above, to describe what a room offers, and expects frozen=True to make it a safe value object. What happens when it runs?
Q2. Larkfield's Facilities context tracks each projector by serial number through repairs and moves between rooms. Its Booking context only lets a member ask for a room that has a projector. How should a projector be modelled in each context?
Q3. A booking type is { status: 'requested' | 'confirmed' | 'cancelled'; doorCode?: string; reason?: string }. Support keeps finding cancelled bookings with no reason. Which change lets the TypeScript compiler refuse them?
Practice only: not graded, not saved, not evidence.

07. Apply it

Use the clinic appointment context from the strategic DDD lessons, or a domain you know well.

  1. List three entities and five value objects, and write the rule that travels with each value, such as 'a slot starts on a quarter hour and lasts 10 to 60 minutes'.
  2. Implement two of the values as frozen dataclasses or TypeScript types, with a test that tries to create an invalid one and expects a refusal.
  3. Model the appointment states (requested, confirmed, checked in, cancelled, no-show) as a discriminated union, run tsc, then add a state and let the compiler list every place that must change.

Keep the code: the skill's practice task builds on it.

08. Review prompt

Without looking back:

  1. What makes two entities the same, and what makes two value objects the same?
  2. Why should a value object check its input in its constructor?
  3. In try_values.py, why can replace() not produce an invalid range?
  4. What does frozen=True not protect against in Python?
  5. How does the never branch in describe turn a forgotten state into a compile error?
  6. Name one place where a plain record is the better choice, and say why.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check