Client validations VS protecting domain consistency

One of the question I often hear about validating the model is why I need to make double validation both UI side and in the domain model itself.

Well, the response is easy, no matter what happens, you need to protect your domain against inconsistencies!

But, first, let’s see the differences between client validations and validating rules inside the domain model.

Validating rules inside the domain models

In many application with a rich domain, the domain model is the heart of everything. This is were all the domain rules lie in. It represents the only source of truth. Everything else is whether a projection of the domain model, infrastructure stuff or utilities.

Having said that, protecting the heart of an application at any cost seems to be a reasonable strategy, doesn’t it?

The domain model can’t trust any information the client sends. It needs to protect its invariant and itself from any inconsistency. It works totally isolated from the rest of the application details and focuses only on the domain behavior and on maintaining the information in a constant valid state.

The domain model doesn’t and shouldn’t care about the client. If wrong information are given to it, it should simply reject it without any form of politeness.

class BookingDates
{
private $departure;
private $return;

public function __construct(DateTime $departure, DateTime $return)
{
if ($departure > $return) {
throw new InvalidDateException('Date of departure must be anterior to date of return');
}

$this->departure = $departure;
$this->return = $return;
}

public function getDeparture()
{
return $this->departure;
}

public function getReturn()
{
return $this->return;
}
}

That’s it. Consistency, consistency, consistency….

The model is not supposed to receive wrong data. But if it does, it is probably an issue from the client which allowed such data to get to the domain layer. So this should be fixed in the client (controller, javascript, whatever).

The model itself will just reject invalid data to prevent from any inconsistency.

Client validations

Client validations are about:

  1. Providing the user with live information he can understand (human readable) about what he is doing;
  2. Make sure we don’t waste time by sending wrong data to the domain layer and then having to explain the frustrated user why he got a “Internal Server Error”;
  3. Saving bandwidth.

But client validations definitely are not enough!

If I was to choose between having client validations or validations inside the domain model. I would definitely go with validating rules inside the domain layer, no matter if the user experience is not friendly.

By chance, we don’t have to choose here, simply do both, and you can sleep well ;-)