Should I validate the domain object properties when they are being set?
In this example I've got a User domain object from my model layer and currently am just validating the type and/or format of the passed in parameter before setting the property, because I have no clue of what should be validated when it comes to domain objects. Some examples would help me understand it.
Is this how I should validate domain object properties or shouldn't I validate them at all?
In the latter case I can then just remove every setter and getter and just make the domain object properties public so I can just interact with them directly.
class User
{
private $id;
private $firstname;
private $lastname;
private $email;
private $password;
private $registerDate;
public function setId($id)
{
if (is_int($id)) {
$this->id = $id;
} else {
throw new Exception('Parameter must be an integer.');
}
}
public function setFirstname($firstname)
{
if (is_string($firstname)) {
$this->firstname = $firstname;
} else {
throw new Exception('Parameter must be a string.');
}
}
//{ etc setters }
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
}