Should the "command" method do the validation?
| Newsgroups | gmane.comp.programming.domain-driven-design |
|---|---|
| Message-ID | <[email protected]> |
Should validation in a domain Entity be implemented as separate method or as part of the Entity state changing method?
For example if I have event booking application where each event has limited number of places for participants. I want to check if user can make the booking or not.
Variation 1:
class Event {
Result add(Booking booking) {
if (fits(booking) {
this.bookings.add(booking)
return Result.success()
}
return Result.fail(NOT_ENOUGHT_PLACES)
}
}
Variation 2:
class Event {
boolean fits(Booking booking) {
...
}
void add(Booking booking) {
bookings.add(booking)
}
}
Variation 3:
class Event {
boolean fits(Booking booking) {
...
}
void add(Booking booking) {
if (!fits(booking) {
throw ConstraintViloationException("Cannot fit booking")
}
bookings.add(booking)
}
}
Variation 1 seems nice but violates the Command and Query separation principle. Variation 2 is fragile because what if client forgets to call the fits() method. Variation 3 seems like duplicating the same check.