Sunday, September 15, 2019

Factories

Shift the responsibility of creating instances of complex objects and AGGREGATES to a separate object, which may itself have no responsibility in the domain model but is still part of the domain design. Provide an interface that encapsulates all complex assembly and that does not require the client to reference the concrete classes of the objects being instantiated. Create entire AGGREGATES as a piece, enforcing their invariants.

When a constructor is all you need

The trade-offs favor a bare, public constructor in the following circunstances:

  • The class is the type. It is not part of any interesting hierarchy, and it isn't used polymorphically by implementing an interface.
  • The client cares about the implementation, perhaps as a way of choosing a STRATEGY.
  • All of the attributes of the object are available to the client, so that no object creation gets nested inside the constructor exposed to the client.
  • The construction is not complicated.
  • A public constructor must follow the same rules as a FACTORY: It must be an atomic operation that satisfies all invariants of the created object.

Avoid calling constructors within constructors of other classes. Constructors should be dead simple. Complex assemblies, especially of AGGREGATES, call for FACTORIES. The threshold for choosing to use a little FACTORY METHOD isn't high.

Eric Evans, "The Life Cycle of a Domain Object", in Domain-Driven Design: Tackling Complexity in the Heart of Software, 129.

No comments

Post a Comment