Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factory Pattern where should this live in DDD?

I have debated this for a while now and still have not come to a conclusion. While most examples I see have the factories code in the application layer I tend to think it should be in the domain layer. Reasons for this: I sometimes have initial validation done in my factory where I want all creation of objects to go through. I want this code to be used on all instantiates of my object. Sometimes an operation requires parameter information which feels unnatural to pass to a constructor. And a few more not as important reasons.

Are there reasons why this is a bad practice? Does this break other patterns?

like image 953
retslig Avatar asked Dec 10 '12 16:12

retslig


People also ask

Where do I put my DDD factory?

A factory should only be present inside the aggregate root, as this is the object that orchestrates all of the business logic. In the context of DDD, the use of a factory pattern is not required to implement the factory design pattern.

Are factories part of the domain?

Factories have nothing to do with the domain of an organisation, but they do form an important part of the domain of an application. It is the domain of the application that is responsible for creating and working with Domain Objects.

What is domain in DDD principle?

Domain-Driven Design(DDD) is a collection of principles and patterns that help developers craft elegant object systems. Properly applied it can lead to software abstractions called domain models. These models encapsulate complex business logic, closing the gap between business reality and code.

What is DDD example?

An aggregate is a domain-driven design pattern. It's a cluster of domain objects (e.g. entity, value object), treated as one single unit. A car is a good example. It consists of wheels, lights and an engine.


4 Answers

I prefer Factories in the Application Layer.

If you keep the Factories in the Domain Layer, they will not help you when you need complex types as parameters (C# code example):

Application Layer:

//this Factory resides in the Domain Layer and cannot reference anything else outside it
Person person = PersonAggregateFactory.CreateDeepAndLargeAggregate(
            string name, string code, string streetName,...
            and lots of other parameters...);

//these ones reside in Application Layer, thus can be much more simple and readable:
Person person = PersonAggregateFactory.CreateDeepAndLargeAggregate(CreatePersonCommand);
Person person = PersonAggregateFactory.CreateDeepAndLargeAggregate(PersonDTO);



Domain Layer:

public class Person : Entity<Person>
{
    public Address Address {get;private set;}
    public Account Account {get;private set;}
    public Contact Contact {get;private set;}
    public string Name {get;private set;}

    public Person(string name, Address address,Account account, Contact contact)
    {
        //some validations & assigning values...
        this.Address = address;
        //and so on...

    }

}

public class Address:Entity<Address>{
    public string Code {get;private set;}
    public string StreetName {get;private set;}
    public int Number {get;private set;}
    public string Complement {get;private set;}
    public Address(string code, string streetName, int number, string complement?)
    {
        //some validations & assigning values...
        code = code;
    }

}

public class Account:Entity<Account>{
    public int Number {get;private set;}

    public Account(int number)
    {
        //some validations & assigning values...
        this.Number = number;
    }

}

//yout get the idea:
//public class Contact...

Also, there is no obligation on keeping Factories inside the Domain Layer (from Domain Driven Design Quickly):

Therefore, shift the responsibility for 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 unit, enforcing their invariants.

As I don't use Factories to load persisted objects into memory, they don't have to be accessible from other layers than Application's. Here's why (from Domain Driven Design Quickly):

Another observation is that Factories need to create new objects from scratch, or they are required to reconstitute objects which previously existed, but have been probably persisted to a database. Bringing Entities back into memory from their resting place in a database involves a completely different process than creating a new one. One obvious difference is that the new object does not need a new identity. The object already has one. Violations of the invariants are treated differently. When a new object is created from scratch, any violation of invariants ends up in an exception. We can’t do that with objects recreated from a database. The objects need to be repaired somehow, so they can be functional, otherwise there is data loss.

like image 94
Alexander Avatar answered Oct 09 '22 12:10

Alexander


+1 for doing that. Accessibility would be a good reason, I would keep the creational code at least close to the domain model layer. Otherwise users of the domain model will get simply confused how to instantiate it specially when finding restricted access constructors. Actually one sound reason to separate it would be that you have different valid ways to create the same thing e.g. which is the case usually when employing the Abstract Factory.

If I had to separate it I would put it in e.g. a package (in the case of Java) at least the same level of the domain model and ship it always along with it e.g.

upper
  --> domain
  --> domain_factory
like image 26
SkyWalker Avatar answered Oct 09 '22 12:10

SkyWalker


A factory in DDD is just an instance of the factory pattern and as such it should be used where it makes the most sense. Another principle to consider is the information expert pattern which essentially states that behavior should be assigned to classes closest to the information. Therefore, if you have some domain specific rules and logic you would like to enforce, place the factory in the domain layer - after all, the factory creates domain objects. Note however that you may have other types of factories in other layers.

like image 34
eulerfx Avatar answered Oct 09 '22 14:10

eulerfx


From memory, Eric Evans' book has examples where object factories are very much part of the domain layer.

For me, it makes perfect sense to locate your factories here.

like image 31
David Osborne Avatar answered Oct 09 '22 14:10

David Osborne