Skip to content

Lesson 7 of 9 · 23m

Domain Modeling With Data and Functions

Use plain objects, constructors, and transition functions instead of class hierarchies — without losing invariants or discoverability.

Classes are not forbidden in functional JavaScript; they are simply a poor default for most domain models. They couple data, behavior, identity, and mutation into one object, then encourage inheritance for variations that are really just data. Plain data plus explicit transition functions keeps the model inspectable, serializable, and easy to test.

Constructors enforce invariants

function createInvoice({ id, customerId, lines }) {
  if (!id) throw new Error("invoice id required");
  if (!Array.isArray(lines) || lines.length === 0) {
    throw new Error("invoice needs at least one line");
  }
  return Object.freeze({ id, customerId, lines, status: "draft" });
}

This is not a class, but it is still a constructor. Its job is to keep invalid values out of the system. Freezing is optional; centralizing construction is the real win.

Behavior becomes transitions

function addLine(invoice, line) {
  assertDraft(invoice);
  return { ...invoice, lines: [...invoice.lines, line] };
}

function assertDraft(invoice) {
  if (invoice.status !== "draft") {
    throw new Error(`cannot modify invoice in ${invoice.status}`);
  }
}

The important detail is not spread syntax. It is that the transition has a name. invoice.status = "paid" scattered through controllers is where invariant bugs breed.

Prefer variants over inheritance

type PaymentMethod =
  | { kind: "card"; token: string }
  | { kind: "bank_transfer"; account: string };

A discriminated union keeps the decision table in one place. Adding a new payment kind becomes a compiler-visible event instead of a hunt through subclasses. Runtime JavaScript can use the same kind convention even without TypeScript.

Serialization is a feature

Plain data can be logged, persisted, diffed, replayed, and sent over a wire. Class instances resist all of that: methods vanish in JSON, private fields complicate cloning, and prototype identity breaks across realms. If your debugging tools cannot print an object, the architecture is fighting operations.

Field notes

  • Name transitions as verbs: issueInvoice, cancelSubscription, applyDiscount.
  • Validate at boundaries, construct through constructors, and trust shapes inside the core.
  • Store facts rather than calculations; totals and derived values belong in pure selectors.
  • Use classes when identity and lifecycle dominate — connections, resources, framework objects — not merely because Java has them.

Was this lesson helpful?

Sign in to rate