Factories

Learn what a factory is and how we can implement it to create complex entities in DDD.

As Eric Evans mentions in his book, there may be occasions when an object’s creation and assembly are complex. Such a process may need to orchestrate a lot of logic to create the complex object. With regards to this, he mentions an example related to the opening of a bank account. This process requires many objects in order to be executed properly. Oftentimes, the logic required to create those objects is not related to business logic, which can mess up the business logic. Refering to the Eric Evan’s example, let us imagine that the aggregate root of the bank account process is Account. Its attributes are a customer entity, which in turn has an address value object and a bankOffice entity, which in turn has an address value object too. Offices addresses exist in a repository, for this reason, it is required to use a repository called officeAddress. To build an Account entity is necessary to load information from external sources, validate the customer information. Interacting with those objects is what adds complexity to objects’ creation. To deal with this situation, DDD suggests that we implement a factory.

What is a factory?

A factory is a tactical pattern used in the DDD world. It helps us create complex objects. It is important to keep in mind that we should only implement this pattern when the instantiation of an object is complex. The use of a factory may add unnecessary complexity.

Despite the help that it offers in the creation of aggregates, a factory does not need to be present inside the domain logic in every aggregate. A factory should only be present inside the aggregate root, as this is the object that orchestrates all of the business logic.

Get hands-on with 1200+ tech skills courses.