Fábrica

Escrito por Darjus Kazakevic · revisado el

Creation has one door, and it checks the rules.

Building a rich object can take several steps, rules and choices of type. Spread across callers, those steps get skipped or run in a different order. A Factory takes the inputs, builds the object, checks the rules, and returns something that is already valid.

In DDD, factories matter most for aggregates. They also keep two paths apart: creating a new aggregate (a new id and a creation event) and rebuilding a stored one from the database (no new id, no event).

En esencia — Put the steps for building a complex object in one place, so it is valid from the moment it exists and no caller ever sees a half-built one.

Cuándo recurrir a él

Recurre a él cuando

  • Creating the object needs rules or steps that must not be skipped
  • You build a whole aggregate, with its inner entities and values
  • The concrete type to build depends on the input

Reconsidéralo cuando

  • Construction is trivial: a plain constructor is clearer
  • DTOs and simple records with no rules to protect
  • A factory that only calls new and adds no checks

Forms of factory

Static factory method (named constructor)
A named creator on the class itself, such as Order.place() or Money.of(). It states intent, can validate, and can return a cached value or a subtype, which a constructor cannot.
Standalone factory
A separate object or function that builds a whole aggregate. Use it when creation needs other services, such as a price list or an id generator.
Creation vs reconstitution
Creating a new aggregate assigns an id and may raise a domain event. Rebuilding one from storage must do neither: it is the same object coming back. Keep separate methods for the two.
In modern TypeScript
A plain function that checks its input and returns a typed object is a factory too: createOrder(input). You only need a class when the object has behaviour of its own.

Reglas de diseño

Return only valid, complete objects
A factory either returns an object that passes every rule, or it throws. If callers must call setters or init() afterwards, the factory has not done its job.
Keep creation and reconstitution apart
place() assigns a new id and raises OrderPlaced. fromRow() rebuilds a stored order with neither. Mixing the two sends a duplicate event every time an order is loaded.
Make the constructor private
If new Order(...) is public, callers can skip the factory and its checks. A private constructor plus named factory methods leaves one way in.

Errores habituales

  • A factory that returns a half-built object, so callers must remember to call init().
  • Raising domain events when loading from the database. The symptom: a duplicate "order placed" email each time an order is loaded.
  • A public constructor next to the factory, so half the code skips the checks.