Creating Identities for Objects in DDD

Edit

To clarify my original problem, I rewrote the question with a more “DDD” contini, common patterns and discussion arguments. The original version can be found in revisions .


Where and how are identities formed for entities / aggregate roots within a domain when DDD is used correctly?

I need to assign unique identifiers to my objects, whether when creating or saving. These identifiers can be in several styles.

  • Calculated (based on the characteristics of the object, therefore, based on the requirements of the business)
  • Natural (based on a specific set of rules, therefore, based on business logic)
  • Surrogates (based on randomly generated values ​​without a business value)

There are many approaches to the task of generating and assigning identifiers: from using factories to create identifiers, delegating to the infrastructure using ORM or generating a database , etc. However, if you correctly use DDD, where and how should identifiers be generated, given that we do not want unfashionable domain models to implement services in essence ?

Requirements above

  • No anemic domain models
  • Essentially no dependency on injection services

Possible approaches

  • Plants
  • Double submission (can it be used to generate identity?)
  • Generation inside repositories
  • Generation within the infrastructure (e.g. ORM or database)
  • Injection services in essence
+5
source share
2 answers

I would put it in a factory. Generating an identifier should not be part of the domain logic, in my opinion, because it is really an infrastructure. You can take id from the database or generate it using uuid or whatever. This is the item. Also remember that only the factory interface belongs to the domain layer, not its implementation.

About your doubts about the factory, if you use a factory to create entities, you should use it everywhere. This is how I do it.

+4
source

Vaughn Vernon's Domain Driven Design Implementation advocate for creating unique identifiers in repositories as follows:

public TenantId nextIdentity() { return new TenantId(UUID.randomUUID().toString().toUpperCase()); } 

TenantId is a value object that wraps an Entity identity.

+5
source

Source: https://habr.com/ru/post/1202144/


All Articles