Domain-Driven Design – Can Domain Entities Manage Other Entities?

design-patternsdomain-driven-designdomain-model

a) As far as I understand it, in most cases Domain Model DM doesn't contain code for creating/deleting domain entities, but instead it is the job of layers ( ie service layer or UI layer ) on top of DM to create/delete domain entities?

b) Domain entities are modelled after real world entities. Assuming particular real world entity being abstracted does have the functionality of creating/deleting other real world entities, then I assume the domain entity abstracting this real world entity could also contain logic for creating/deleting other entities?

class RobotDestroyerCreator
{
         ...
         void heavyThinking()
         {
                  ...
                  if(...) 
                        unitOfWork.registerDelete(robot);
                  ...

                  if(...)
                  {
                         var robotNew = new Robot(...); 
                         unitOfWork.registerNew(robotNew);  
                  {
                  ...
          }
}

Thank you

Best Answer

a) DDD doesn't specify that domain objects shouldn't create domain objects. A domain object can very well create another domain object. An aggregate is responsible for enforcing a consistency boundary around a cluster of entities and value objects. As such, it could very well have behaviors which create entities. For example, the stereotypical sales order aggregate can create instances of order line entities (or value objects, depending on implementation). The important thing is to ensure that domain and entities are created or deleted in well defined places. Take a look at this article which evaluates aggregate creation in a domain model.

b) The mapping between a real world entity and the corresponding abstraction in code is never isomorphic. Abstractions in code are bound by technical constraints that cannot be overlooked. Code isn't meant to be an isomorphism of reality, it is only meant exhibit functional characteristics which fulfill sets of requirements. The similarity between reality and code is an aspect that we strive for to streamline the development process. In other words, if a real world entity creates something, it doesn't immediately translate to the corresponding abstraction in code, though it may - there is no hard rule.