Domain Driven Design and the role of the factory class

Th3Fix3r picture Th3Fix3r · Feb 17, 2009 · Viewed 25.9k times · Source

I'am unclear as to what the roles and responsibility of the factory class is. I know enough that the factory class should be resposible for the creation of domain objects (aggregate root) along with its associated entities and value objects.

But what is not clear to me is where the factory "layer" lies with a DDD architecture? Should the factory be calling directly into the repository to get its data or the service library?

Where does the factory fit into the following framework:
UI > App > Domain > Service > Data

Also, because the factory is the only place allowed for object creation would'nt you get circular references if you wanted to create your objects in your data and service layers?

If the role of the factory class is for object creation then what benefits does the service layer have?

I've asked a lot of questions and appreciate any response. What i'am lacking is a sample application which demonstrates how all the layers in a domain driven design project come together...Is there anything out there?

Answer

moffdub picture moffdub · Feb 21, 2009

But what is not clear to me is where the factory "layer" lies with a DDD architecture? Should the factory be calling directly into the repository to get its data or the service library?

The factory should be the one-stop shop to construct domain objects. Any other part of the code that needs to do this should use the factory.

Typically, there are at least three sources of data that are used as input into a factory for domain object construction: input from the UI, the results of queries from persistence, and domain-meaningful requests. So to answer your specific question, the repository would use the factory.

Here is an example. I am using Holub's Builder pattern here. Edit: disregard the use of this pattern. I've started realizing that it doesn't mix too well with DDD factories.

// domain layer
class Order
{
    private Integer ID;
    private Customer owner;
    private List<Product> ordered;

    // can't be null, needs complicated rules to initialize
    private Product featured; 

    // can't be null, needs complicated rules to initialize, not part of Order aggregate
    private Itinerary schedule; 

    void importFrom(Importer importer) { ... }

    void exportTo(Exporter exporter) { ... }

    ... insert business logic methods here ...

    interface Importer
    {
        Integer importID();
        Customer importOwner();
        Product importOrdered();
    }

    interface Exporter
    {
        void exportID(Integer id);
        void exportOwner(Customer owner);
        void exportOrdered(Product ordered);
    }
}

// domain layer
interface OrderEntryScreenExport { ... }

// UI
class UIScreen
{
    public UIScreen(OrderEntryDTO dto) { ... }
}

// App Layer
class OrderEntryDTO implements OrderEntryScreenExport { ... }

Here is what the OrderFactory might look like:

interface OrderFactory
{
    Order createWith(Customer owner, Product ordered);
    Order createFrom(OrderEntryScreenExport to);
    Order createFrom(List<String> resultSets);
}

The logic for the featured Product and the generation of the Itinerary go in the OrderFactory.

Now here is how the factory might be used in each instance.

In OrderRepository:

public List<Order> findAllMatching(Criteria someCriteria)
{
    ResultSet rcds = this.db.execFindOrdersQueryWith(someCriteria.toString());
    List<List<String>> results = convertToStringList(rcds);

    List<Order> returnList = new ArrayList<Order>();

    for(List<String> row : results)
        returnList.add(this.orderFactory.createFrom(row));

    return returnList;
}

In your application layer:

public void submitOrder(OrderEntryDTO dto)
{
    Order toBeSubmitted = this.orderFactory.createFrom(dto);

    this.orderRepo.add(toBeSubmitted);

    // do other stuff, raise events, etc
}

Within your domain layer, a unit test perhaps:

Customer carl = customerRepo.findByName("Carl");
List<Product> weapons = productRepo.findAllByName("Ruger P-95 9mm");
Order weaponsForCarl = orderFactory.createWith(carl, weapons);

weaponsForCarl.place();

assertTrue(weaponsForCarl.isPlaced());
assertTrue(weaponsForCarl.hasSpecialShippingNeeds());

Where does the factory fit into the following framework: UI > App > Domain > Service > Data

Domain.

Also, because the factory is the only place allowed for object creation would'nt you get circular references if you wanted to create your objects in your data and service layers?

In my example, all dependencies flow from top to bottom. I used the Dependency Inversion Principle (PDF link) to avoid the problem you speak of.

If the role of the factory class is for object creation then what benefits does the service layer have?

When you have logic that doesn't fit into any single domain object OR you have an algorithm that involves orchestrating multiple domain objects, use a service. The service would encapsulate any logic that doesn't fit in anything else and delegate to domain objects where it does fit.

In the example I scribbled here, I imagine that coming up with an Itinerary for the Order would involve multiple domain objects. The OrderFactory could delegate to such a service.

BTW, the hierarchy you described should probably be UI > App > Domain Services > Domain > Infrastructure (Data)

I've asked a lot of questions and appreciate any response. What i'am lacking is a sample application which demonstrates how all the layers in a domain driven design project come together...Is there anything out there?

Applying Domain Driven Design and Patterns by Jimmy Nilsson is a great compliment to Eric Evans' Domain-Driven Design. It has lots of code examples, though I don't know if there is an emphasis on layering. Layering can be tricky and is almost a topic separate from DDD.

In the Evans book, there is a very small example of layering you might want to check out. Layering is an enterprise pattern, and Martin Fowler wrote Patterns of Enterprise Application Architecture, which you might find useful too.