Leonardo
Leonardo

Reputation: 11387

DDD - Is Aggregate root as factory ok?

Is it ok for my aggregate root to act as a factory for entities that he manages?

E.G: is it ok for my aggregate root "Question" to instantiate a entity "Answer"?

Upvotes: 2

Views: 1957

Answers (2)

VoiceOfUnreason
VoiceOfUnreason

Reputation: 57194

Is it ok for my aggregate root to act as a factory for entities that he manages?

Almost.

The aggregate root isn't an entity as such, but a role played by an entity. Think interface - it gives the application a restricted access to the domain model, encapsulating the actual implementation.

It's natural to have the aggregate be responsible for its own state; after all, all of the components of the aggregate are going to be drawn from the same data model (they are persisted together).

Within your entity (which is acting as the aggregate root), you want your code to align as closely as possible with the language of the domain. That will usually mean that you don't have a "factory", as in the design pattern, but instead have some entity in the model that produces the managed entities.

Udi Dahan touched on this, somewhat obliquely, when he wrote Don't Create Aggregate Roots.

Customers don’t just appear out of thin air.

The entities in your model all come from other entities in your model. Turtles all the way down.

So introducing the factory design pattern into the domain language is a bit sketch.

Because the domain model lives in memory... because its unusual for the domain model to have side effects... a lot of the usual motivations for abstracting connection points don't apply. If you find yourself, for example, wanting to inject a mock into your domain model for unit testing, then something has gone badly wrong (into domain services, yes, but not into entities).

Upvotes: 3

Constantin Galbenu
Constantin Galbenu

Reputation: 17673

Yes, it is, if the code is a simple new Answer (someArguments, ...).

If it is a more complicated process then you should extract this code into a AnswerFactory class.

EDIT: The desire to create a clean code dictates this and not DDD. A rule from DDD that is relevant to your question is that Domain (so all classes from the Domain layer) should not depend on any other layers (like Infrastructure or Application).

Upvotes: 1

Related Questions