I'm just learning DDD and a question raised in my mind about unique identifiers in an entity.
Consider this simple method that checks the uniqueness of an entity to prevent duplication:
private bool IsDuplicate(BoardGame boardGame)
{
//It's either this
if (Games.Any(x => x.Id == boardGame.Id)) return true;
//Or this
if (Games.Any(x => x.Name == boardGame.Name && x.Price == boardGame.Price)) return true;
return false;
}
The first method is very clean and readable. The problem is we usually don't have the value of Id before the item is persisted somehow because it is handled by the ORM.
The second method is the way how an object is considered unique from a domain point of view. We can evaluate this uniqueness before persisting the object But the downside is it gets messy when an entity's uniqueness becomes more complicated.
Now the question is, isn't that Id field redundant? don't we have to check this uniqueness with domain perspective anyway? why not having, say, a composite/compound key in ORM/Persistence side?
Of course this is an example. The name or price could change, but remember, I said that in the domain perspective, the name should be unique.
Consider having a Member entity, with his/her SSN as a unique identifier.
BoardGame
that requires it to be unique? If the only answer to that question is "persist/retrieve it", then are we really talking about our domain anymore? Identity is a term that is most relevant when we are talking about storage. Between the moment when aBoardGame
is retrieved and the moment it is persisted (i.e. during our business logic), it's uniqueness is nothing more than a persistence artifact. Methods likeIsDuplicate
are usually an indicator of incomplete design.