Search code examples
c#design-patternsdomain-driven-designarchitectural-patterns

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?


Solution

  • +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