Let's say I wan't to update a nickName of Person entity, with rule that this nickName is used by up to 5 other Persons. How should I do it?
Should I do validation in domain service, before calling an update?
Or is it better to pass a personRepository into PersonEntity.update(...) method, and do the search and validation inside entity update method?
Additional clarification:
@plalx idea of creating additional entity for executing this rule is clever.
When I am reading about DDD I often read that passing a repository into entity is not recomended (if not evil). That's why I try to find an example where we need a repository or some other service in entity). I actually don't know if only passing repository is bad and service is ok, or passing a service into entity is similarily discouraged.
Let's assume that this rule is not so hard and important business rule, and we can have multiple similar rules (so many, that creating an additional entity for each rule for each attribute we want to validate is a little bit overengineered). Lets assume we can allow 6 or 7 same nicknames in case of concurrent update (we only want to limit them to reasonably small number) and check of
personRepository.usageOfNickname(this/person.nickname) < 5
is sufficient. In such a case, which design is better from DDD point of view?
passing personRepository into Person Entity
class Person { ... boolean changeNickname(newNickname, nicknameUsageService) { if (personRepository.usageOfNickname(this.nickname) < 5) { this.nickname = newNickname; return true; } else { return false; //or throw } } }
this seems most obvious and straighforwad to me, benefit is that logic is enclosed in Entity, but what bothers me is this wretched passing of repository into entity and this sense that this is discouraged by Evans
instead of passing personRepository into Person Entity passing personService into Person Entity (similar as in example of @plalx) - is passing a service into Entity anyhow better than a repository?
- doing validation in service similar as in @plalx sample
changePersonNickname(personId, newNickname){...}
but in @plalx's sample using a service seems justified, as it operates on two Entities, here we have only one Entity and I'm afraid if putting this logic in service instead of in Entity it concerns wouldn't be going towards Anemic Domain Model and leaving DDD.