Software Architecture

Domain-Driven Design: Factories, object creation and invariants from the start

Learn when to use a constructor, static method, or dedicated Factory to create complete domain objects. Build an order from a quote in TypeScript, check its invariants, and distinguish new creation from reconstituting persisted state.

Updated on October 29, 2026

Content explored 0%
18px

The indicator keeps the furthest percentage explored; marking the article complete is your choice.

A store converts a quote into an order. The code first creates an empty Order, then assigns the customer, copies lines, calculates prices, and sets the status. Another process copies almost the same sequence, but forgets to check that the quote is still valid.

During construction, orders exist without customers or lines. If someone publishes them in a shared collection, saves them too early, or leaves an exception halfway through, the rest of the system may receive an incomplete object.

A Factory gives that creation a name and boundaries: it receives what it needs and delivers a complete object satisfying initial rules, or rejects the operation. It does not need to save, charge, or respond over HTTP to fulfill that role.

What responsibility a Factory assumes

In DDD, a Factory encapsulates the construction of objects or Aggregates when that task exposes complexity the consumer should not manage. The result must be complete and satisfy its Invariants, the conditions defining its valid states. Evans develops this responsibility in the Factories section of his DDD reference.

The Factory protects the beginning; the created object must protect its evolution. If a Factory constructs an order correctly, but any consumer can later delete its confirmed lines, the model still has a problem.

Nor should there be one universal class constructing every object. An operation such as fromAcceptedQuote() expresses a specific intention; createObject(type, data) requires interpreting codes and data combinations that can hide different rules.

A DDD Factory does not require implementing a class hierarchy or necessarily reproducing the GoF patterns named Factory Method or Abstract Factory. Here we care about the responsibility of constructing the model; the chosen form must respond to actual complexity.

When a constructor is enough

If constructing a value only requires checking a local condition, a constructor may be clear and sufficient. For example, to represent a positive number of seats:

// Programa autocontenido: seats.ts.
import assert from 'node:assert/strict';

class Seats {
  readonly count: number;

  constructor(count: number) {
    if (!Number.isSafeInteger(count) || count <= 0) {
      throw new Error('Las plazas deben ser un entero positivo');
    }
    this.count = count;
    Object.freeze(this);
  }
}

assert.equal(new Seats(20).count, 20);
assert.throws(() => new Seats(0), /entero positivo/);

A SeatsFactory.createSeats() that merely calls that constructor does not necessarily add a new decision. Having parameters does not automatically make creation complex either.

Look for another form when the consumer must coordinate components, choose variants, establish initial rules, or remember a sequence that should not be repeated throughout the application.

A static method can express intention

A constructor offers only the class name. A static method lets you name the creation form. Fowler shows this possibility in Replace Constructor with Factory Function.

In reservations, BookingWindow.between(start, end) may be more expressive than an ambiguous constructor with numbers. This program is independent of the rest:

// Programa autocontenido: booking-window.ts.
import assert from 'node:assert/strict';

class BookingWindow {
  readonly startMs: number;
  readonly endMs: number;

  private constructor(startMs: number, endMs: number) {
    if (!Number.isSafeInteger(startMs) || !Number.isSafeInteger(endMs) ||
      startMs < 0 || endMs <= startMs) {
      throw new Error('La ventana necesita inicio y fin válidos');
    }
    this.startMs = startMs;
    this.endMs = endMs;
    Object.freeze(this);
  }

  static between(startMs: number, endMs: number): BookingWindow {
    return new BookingWindow(startMs, endMs);
  }
}

assert.equal(BookingWindow.between(1000, 2000).endMs, 2000);
assert.throws(() => BookingWindow.between(2000, 1000), /inicio y fin/);

We use nonnegative integer millisecond instants for this demonstration. We are not solving local schedules, calendars, or room availability. A valid window is a condition for booking, not a granted reservation.

This example teaches that you can improve creation without introducing a separate Factory class. The name helps express the agreement; it does not replace validations.

Main example: create an order from a quote

From a fragile sequence to a complete operation

The problematic alternative often resembles this partial snippet with a fictional setter API:

const order = new MutableOrder();
order.setCustomerId(quote.customerId);
order.setSourceQuoteId(quote.id);
for (const line of quote.lines) {
  order.addLine(line.productId, line.quantity, line.unitPriceMinorUnits);
}
order.setStatus('draft');

The consumer knows the assembly order and can forget steps. The improvement will be factory.fromAcceptedQuote(orderId, quote): all construction happens before delivering the order.

Initial rules and simplifications

The store allows converting an approved quote while it remains within its conversion window. We establish that:

  • The quote has accepted status and the current instant is before its expiration.
  • The order starts in draft, with customer, quote reference, and at least one line.
  • Each line has a local identifier, product, positive quantity, and valid price.
  • Neither products nor line identifiers repeat.
  • Monetary calculations must remain within the safe integer range.

All prices are EUR cents. There are no discounts, taxes, charges, stock, or global uniqueness guarantees. The Use Case provides the order identifier and obtains a trustworthy quote; the Factory does not query providers to gather that data.

The clock will be an explicit dependency. This lets us check the exact expiration boundary without waiting or changing the system clock.

Complete program and tests

Save the following block as order-factory.test.ts. Run it with node --test order-factory.test.ts using Node.js 24.21.0, without external packages.

The previous programs run with node seats.ts and node booking-window.ts on the same version. Direct execution uses type stripping, which removes TypeScript annotations but does not perform static type checking.

import assert from 'node:assert/strict';
import test from 'node:test';

function requireText(value: string): string {
  if (typeof value !== 'string' || !value.trim()) throw new Error('Identificador vacío');
  return value.trim();
}

class Money {
  readonly minorUnits: number;
  constructor(minorUnits: number) {
    if (!Number.isSafeInteger(minorUnits) || minorUnits < 0) {
      throw new Error('Importe EUR inválido');
    }
    this.minorUnits = minorUnits;
    Object.freeze(this);
  }
}

class OrderItem {
  readonly id: string;
  readonly productId: string;
  readonly quantity: number;
  readonly unitPrice: Money;

  constructor(id: string, productId: string, quantity: number, unitPrice: Money) {
    if (!Number.isSafeInteger(quantity) || quantity <= 0) {
      throw new Error('Cantidad inválida');
    }
    this.id = requireText(id);
    this.productId = requireText(productId);
    this.quantity = quantity;
    this.unitPrice = unitPrice;
    Object.freeze(this);
  }

  totalMinorUnits(): number {
    return new Money(this.quantity * this.unitPrice.minorUnits).minorUnits;
  }
}

type OrderSnapshot = {
  id: string;
  customerId: string;
  sourceQuoteId: string;
  createdAtMs: number;
  status: 'draft' | 'confirmed';
  lines: { id: string; productId: string; quantity: number; unitPriceMinorUnits: number }[];
};

class Order {
  #id: string;
  #customerId: string;
  #sourceQuoteId: string;
  #createdAtMs: number;
  #status: 'draft' | 'confirmed';
  #lines: readonly OrderItem[];

  private constructor(state: OrderSnapshot, lines: readonly OrderItem[]) {
    this.#id = requireText(state.id);
    this.#customerId = requireText(state.customerId);
    this.#sourceQuoteId = requireText(state.sourceQuoteId);
    if (!Number.isSafeInteger(state.createdAtMs) || state.createdAtMs < 0) {
      throw new Error('Instante de creación inválido');
    }
    if (state.status !== 'draft' && state.status !== 'confirmed') {
      throw new Error('Estado desconocido');
    }
    if (lines.length === 0) throw new Error('El pedido necesita líneas');
    if (new Set(lines.map(line => line.id)).size !== lines.length ||
      new Set(lines.map(line => line.productId)).size !== lines.length) {
      throw new Error('Líneas o productos duplicados');
    }
    let total = 0;
    for (const line of lines) total = new Money(total + line.totalMinorUnits()).minorUnits;
    this.#createdAtMs = state.createdAtMs;
    this.#status = state.status;
    this.#lines = Object.freeze([...lines]);
  }

  static start(state: Omit<OrderSnapshot, 'status'>): Order {
    return Order.restore({ ...state, status: 'draft' });
  }

  static restore(state: OrderSnapshot): Order {
    const lines = state.lines.map(line => new OrderItem(
      line.id, line.productId, line.quantity, new Money(line.unitPriceMinorUnits),
    ));
    return new Order(state, lines);
  }

  confirm(): void {
    if (this.#status !== 'draft') throw new Error('El pedido ya está confirmado');
    this.#status = 'confirmed';
  }

  snapshot(): OrderSnapshot {
    return {
      id: this.#id, customerId: this.#customerId, sourceQuoteId: this.#sourceQuoteId,
      createdAtMs: this.#createdAtMs, status: this.#status,
      lines: this.#lines.map(line => ({
        id: line.id, productId: line.productId, quantity: line.quantity,
        unitPriceMinorUnits: line.unitPrice.minorUnits,
      })),
    };
  }
}

type Quote = {
  id: string;
  customerId: string;
  status: 'draft' | 'accepted';
  expiresAtMs: number;
  lines: { productId: string; quantity: number; unitPriceMinorUnits: number }[];
};

interface Clock { nowMs(): number; }

class OrderFactory {
  #clock: Clock;
  constructor(clock: Clock) { this.#clock = clock; }

  fromAcceptedQuote(orderId: string, quote: Quote): Order {
    const now = this.#clock.nowMs();
    if (!Number.isSafeInteger(now) || now < 0 ||
      !Number.isSafeInteger(quote.expiresAtMs) || quote.expiresAtMs < 0) {
      throw new Error('Instantes inválidos');
    }
    if (quote.status !== 'accepted') throw new Error('La cotización no está aprobada');
    if (now >= quote.expiresAtMs) throw new Error('La cotización venció');

    return Order.start({
      id: orderId, customerId: quote.customerId, sourceQuoteId: quote.id,
      createdAtMs: now,
      lines: quote.lines.map((line, index) => ({
        id: `line-${index + 1}`, productId: line.productId,
        quantity: line.quantity, unitPriceMinorUnits: line.unitPriceMinorUnits,
      })),
    });
  }
}

function acceptedQuote(): Quote {
  return {
    id: 'quote-1', customerId: 'customer-7', status: 'accepted', expiresAtMs: 2000,
    lines: [
      { productId: 'book', quantity: 2, unitPriceMinorUnits: 1200 },
      { productId: 'notebook', quantity: 1, unitPriceMinorUnits: 300 },
    ],
  };
}

test('la Factory entrega un pedido completo y no comparte datos de entrada', () => {
  const factory = new OrderFactory({ nowMs: () => 1000 });
  const quote = acceptedQuote();
  const order = factory.fromAcceptedQuote('order-1', quote);
  const snapshot = order.snapshot();
  assert.equal(snapshot.status, 'draft');
  assert.equal(snapshot.customerId, 'customer-7');
  assert.equal(snapshot.createdAtMs, 1000);
  assert.deepEqual(snapshot.lines.map(line => line.id), ['line-1', 'line-2']);
  assert.equal(snapshot.lines.reduce((sum, line) =>
    sum + line.quantity * line.unitPriceMinorUnits, 0), 2700);
  quote.lines[0].quantity = 99;
  assert.equal(order.snapshot().lines[0].quantity, 2);
});

test('se comprueban las precondiciones y el vencimiento exacto', () => {
  const quote = acceptedQuote();
  assert.throws(() => new OrderFactory({ nowMs: () => 1000 })
    .fromAcceptedQuote('order-1', { ...quote, status: 'draft' }), /aprobada/);
  assert.throws(() => new OrderFactory({ nowMs: () => 2000 })
    .fromAcceptedQuote('order-1', quote), /venció/);
});

test('el Aggregate rechaza un estado inicial inválido incluso sin la Factory dedicada', () => {
  const factory = new OrderFactory({ nowMs: () => 1000 });
  const quote = acceptedQuote();
  assert.throws(() => factory.fromAcceptedQuote('order-1', { ...quote, lines: [] }), /líneas/);
  assert.throws(() => factory.fromAcceptedQuote('order-1', {
    ...quote, lines: [quote.lines[0], quote.lines[0]],
  }), /duplicados/);
  assert.throws(() => factory.fromAcceptedQuote('order-1', {
    ...quote, lines: [{ ...quote.lines[0], quantity: 0 }],
  }), /Cantidad/);
  assert.throws(() => Order.start({
    id: 'order-2', customerId: 'customer-7', sourceQuoteId: 'quote-1',
    createdAtMs: 1000, lines: [],
  }), /líneas/);
});

test('reconstituir conserva estado e identidad sin volver a aprobar la creación', () => {
  const original = new OrderFactory({ nowMs: () => 1000 })
    .fromAcceptedQuote('order-1', acceptedQuote());
  original.confirm();
  const saved = original.snapshot();
  const restored = Order.restore(saved);
  assert.notEqual(restored, original);
  assert.deepEqual(restored.snapshot(), saved);
  assert.throws(() => restored.confirm(), /ya está confirmado/);
});

How construction is distributed

The input contains two books at 12 EUR and a notebook at 3 EUR, with a quote approved until instant 2000. The clock returns 1000. The Factory checks that precondition, assigns local identifiers to the lines, and requests a new draft order with an implicit total of 27 EUR.

The seats.ts and booking-window.ts programs completed their assertions, and the four order-factory.test.ts tests passed with Node.js 24.21.0. No static TypeScript analysis or persistence or external integration tests were performed.

The Aggregate validates its structure: nonempty references, valid lines, distinct products, and representable calculations. The dedicated Factory is not permitted to bypass those conditions. start() is also a creation method and accepts only the agreed initial state.

We internally reuse restore() to construct components and check common state. That does not make creation and reconstitution the same business operation: start() fixes draft; restore() preserves the received state. There is no expiration logic or creation effects inside restore().

If a line is invalid, the consumer does not receive an incomplete order. Local objects may have been created and then discarded, but nothing has been saved or published. This in-memory construction property is not equivalent to a distributed transaction and does not reverse external effects someone adds later.

Object Invariants and creation preconditions

It is useful to distinguish two rule types. “Every order has valid lines” must also hold when reconstructing it. “This quote is still available for conversion now” is evaluated only when starting that process.

A Factory that checks everything and returns an object with unrestricted setters leaves Invariants unprotected. At the opposite extreme, requiring reconstruction of a historical order under today's commercial conditions may prevent loading perfectly legitimate data.

The example accepts typed, known snapshots, not arbitrary JSON. A real adapter would validate structure and version before reconstruction. If structural rules change, decide how to interpret or migrate historical states; reconstitution does not mean blindly trusting any saved data.

A private constructor restricts calls during TypeScript checking, but is not a runtime security boundary. The TypeScript class documentation distinguishes those restrictions from # private fields. Retain validations and also control your code's public inputs.

Education: a Domain object can create another

A course offering can offer createEnrollment() if it knows its opening conditions and can start an enrollment with the correct reference to that offering. This snippet shows only a class method, not an independent program:

createEnrollment(enrollmentId: string, studentId: string): Enrollment {
  this.requireOpenForEnrollment();
  return Enrollment.start(enrollmentId, studentId, this.id);
}

Here we assume requireOpenForEnrollment() checks that enrollment is open and Enrollment.start() establishes its initial conditions. The creator object contributes knowledge it already has; it should not start querying APIs or loading others' histories merely to keep the method inside the class.

Creating the enrollment also does not guarantee a place, prevent global duplicates, or save it. If capacity is a constraint, the process assigning it needs its own guarantee. This case teaches recognizing when a creation method naturally belongs to an existing object and what promises it must not make.

What a Factory should not absorb

A class that queries a quote over HTTP, charges a card, creates the order, saves it, and sends an email coordinates much more than construction. Separating these tasks lets you know which conditions were checked and which failures can leave pending effects.

A Use Case can obtain the data, invoke the Factory, and coordinate saving. Technical access remains in its adapters. A Factory can collaborate with a Domain policy when creation requires it; it need not become a general application service.

If data comes from another Bounded Context, keep their implementations separate. An HTTP ACL integration with a consumer contract can deliver necessary information. The Factory does not turn that query and subsequent saving into a shared transaction.

Nor does it guarantee a quote is converted to an order only once. Two calls can create two valid objects with different identifiers. If the business requires a single conversion, the system must protect it when recording the operation through appropriate uniqueness or concurrency mechanisms.

When to choose each form

Use a constructor when creation is brief, its parameters have clear meaning, and it can independently guarantee a valid state.

Prefer a static method when it helps distinguish intentions, fix initial values, or name creation alternatives. Do not automatically call it Factory Method in the GoF pattern sense: a named static method does not imply a polymorphic hierarchy.

Consider a dedicated Factory when assembling several components, variants, or creation collaborations obscures the main object's intention. Its responsibility should be describable without including saving, notifying, and responding to the user.

And use a Domain object as creator when it already has suitable knowledge and the operation is a natural part of its responsibility. No form requires abstracting ten other possibilities that do not yet exist.

Prompts to guide and review Factories with AI

Evaluate whether actual creation complexity exists

Analyze these construction sequences. For each, propose a constructor, static method, creation from an existing object, or dedicated Factory. Justify which complexity it hides and which initial rules it guarantees. Do not modify files or add hierarchies by default. A person will validate business intentions and whether the differences are real or merely different names for the same thing.

Implement complete construction

Implement OrderFactory.fromAcceptedQuote in TypeScript without dependencies. Receive the order identifier, approved quote, and explicit clock. Reject exact expiration, create valid lines, and return a complete draft order. Do not query HTTP, charge, save, or notify. Also retain structural validations in the Aggregate. Provide code and tests for invalid inputs and not sharing mutable state. A person will run the tests and validate the conversion policy.

Review creation and reconstitution

Review these creation and restore paths. Look for identity regeneration, loss of confirmed state, applying current expirations to historical data, and external effects inside constructors. Do not change files. Return evidence and observable scenarios; distinguish questions from errors. A person will check the persisted format and historical rules before deciding migrations or exceptions.

AI may generate a Factory that merely wraps new or, conversely, a class concentrating the entire process. Review the concrete responsibility and paths that could deliver incomplete objects, not just the filename.

Three exercises with reasoned solutions

1. An expired quote and a historical order

An order was created yesterday from a quote valid at that time. Today the Factory rejects converting it because it expired. Should loading the existing order also fail?

Reasoned solution: not for that reason. Reconstitution preserves the identity, date, and state already recorded; it does not attempt another conversion. It must validate integrity conditions applicable to saved state and handle historical versions explicitly, without charging again or querying the quote's current validity.

2. Twenty Factories that only call constructors

AI creates a Factory for each Value Object, all without additional decisions or dependencies. What would you review?

Reasoned solution: the responsibility they add and cost they introduce. If they merely duplicate a clear call, a constructor or static method may suffice. Keep an abstraction when it hides a real decision or establishes a useful contract, not to complete a pattern checklist.

3. An email sent before completion

The Factory sends an “order created” email and then discovers a duplicate line. Is throwing an exception enough?

Reasoned solution: no; the exception does not withdraw the email. Construct and validate before starting external effects, and coordinate notifications with the process's durable outcome according to its needs. A construction Factory should not promise that saving and notifying always happen together.

How to recognize a useful Factory

Look for a creation operation with clear intention, explicit inputs, and a complete result. Check that errors do not expose partially configured objects and that rules do not depend on every consumer remembering a setter sequence.

Then review boundaries: creating is not saving, validating a precondition is not reserving a resource, and reconstitution is not starting another life. A well-placed Factory hides necessary complexity without absorbing others' responsibilities or replacing protection of the object it constructs.

Loading conversation…

Keep learning