When validating a domain entity, is it better to validate the values as they are set, or all at once with a validator (such as in Symfony2) later on?
For example:
Option 1. Validate while being set
public function setEmail($email)
{
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new EntityException('The specified email address ' . $email . ' is invalid.');
}
$this->_email = $email;
return $this;
}
Option 2. Validate later…
$user = new UserEntity();
$user->setEmail('johnnie@duh.com');
$validator = new Validator();
$validator->validate($user);
Option 3. Both of the above (although seems a little redundant and not worth the overhead).
I know that the first one probably makes for more airtight entities, but the second one makes for more user friendly error handling.
Also, the second option seems easier to configure and maintain…as I don’t have to adjust the setters, and I can centralize my validation logic to a single class.
What it boils down to…
So basically, it sounds like Option 2 is what I WANT to do, but feel like sacrificing the airtight-ness of the entity (for example, if I forget to run the entity through the validator), might be stupid.
Single Responsibility Principle
The best is to have all necessary validations in a separated layer. With that will be easier to maintain and test the validators. Also easier to validate data across your application.
Don’t Repeat Yourself
You don’t have to call validate() for each entity.
All you have to do is to implement the validation on your repository layer or service layer if you have one.
So in your user’s repository
And the common validation for all entities: