Implement validations in the domain model layer Validations are usually implemented in domain entity constructors or in methods that can update the
entity. There are multiple ways to implement validations, such as verifying data and raising exceptions
if the validation fails. There are also more advanced patterns such as using the Specification pattern
for validations, and the Notification pattern to return a collection of errors instead of returning an
exception for each validation as it occurs.
Validate conditions and throw exceptions The following code example shows the simplest approach to validation in a domain entity by raising
an exception. In the references table at the end of this section you can see links to more advanced
implementations based on the patterns we have discussed previously.
public void
SetAddress
(Address address)
{
_shippingAddress = address??
throw new ArgumentNullException
(
nameof
(address));
}
A better example would demonstrate the need to ensure that either the internal state did not change,
or that all the mutations for a method occurred. For example, the following implementation would
leave the object in an invalid state:
public void
SetAddress
(
string
line1,
string
line2,
string
city,
string
state,
int
zip)
{
_shippingAddress.
line1
= line1 ??
throw new ...
_shippingAddress.
line2
= line2;
_shippingAddress.
city
= city ??
throw new ...
_shippingAddress.
state
= (
IsValid
(state) ? state :
throw new …);
}
If the value of the state is invalid, the first address line and the city have already been changed. That
might make the address invalid.
A similar approach can be used in the
entity’s constructor, raising an exception to make sure that the
entity is valid once it is created.