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.
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';
classSeats {
readonlycount: number;
constructor(count: number) {
if (!Number.isSafeInteger(count) || count <= 0) {
thrownewError('Las plazas deben ser un entero positivo');
}
this.count = count;
Object.freeze(this);
}
}
assert.equal(newSeats(20).count, 20);
assert.throws(() =>newSeats(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:
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 = newMutableOrder();
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.
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:
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.
Integrate the collection by building an order API with TypeScript, Express, Zod, and SQLite. Includes project files, domain rules, events, version control, Vitest tests, and commands to run and verify it locally.
Learn to guide AI agents with business rules, context boundaries, and verifiable criteria. A TypeScript case shows how to prepare instructions, protect Order, design tests, and review changes without delegating architectural judgment.
Compare a modular monolith with separating Sales, Payments, and Inventory. Design contracts in TypeScript and Express and understand partial failures, eventual consistency, idempotency, Outbox, and Sagas without introducing complex infrastructure.