To further clarify my initial problem, I rewrote the question with more 'DDD'-termini, common patterns and discussion arguments. The orginal version can be found under revisions.
Where and how are identities for entities/aggregate roots being generated inside the domain when correctly applying DDD?
I need to assign unique identities to my entities, either upon creation or persisting. Those identities can come in several styles
There are many approaches for the task of generation and assignment of identities, from using factories to create identities, delegation to the infrastructure using ORM or database generation etc. However, if correctly applying DDD, where and how should identities be generated, considering that we don't want anemic domain models and injection of services into entities?
A domain entity in DDD must implement the domain logic or behavior related to the entity data (the object accessed in memory). For example, as part of an order entity class you must have business logic and operations implemented as methods for tasks such as adding an order item, data validation, and total calculation.
In the context of DDD, identity is something inherent to an entity. Only entities have it; it's something that uniquely identifies them among all other entities. For example, we deem two people as being different regardless of any "attributes" they possess.
Ids in domain entities is a design smell. In most cases, they indicate poor entity encapsulation. If you want proper separation of concerns, you should reduce the number of Ids in your domain entities to as low as possible. Heavy Ids usage is common for anemic model.
Entities are Domain concepts that have a unique identity in the problem domain. Entities represent domain objects and are primarily defined by their identity, continuity, and persistence over time, and not only by the attributes that comprise them.
I would place it in a factory. Generating id shouldn't be a part of domain logic in my opinion, because it's really an infrastructure matter. You can take id from DB or generate it with uuid or whatever. It's a detail. Also remember that only interface of a factory belongs to domain layer, not its implementation.
About your doubts for factory, if you use factory to create entities then you should use it everywhere. This is how I do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With