Skip to content

05. Fail Fast Validations

Andre Baltieri edited this page Nov 7, 2017 · 2 revisions

Fail Fast Validations

You can use IValidatable interface to explicit that a class must have a Validate method and use it to fail even before you arrive your Domain and Business Rules.

Let's implement it:

public class CreateCustomerCommand : Notifiable, IValidatable
{
    public string FirstName { get; private set; }
    public string LastName { get; private set; }

    public void Validate()
    {
        AddNotifications(new Contract()
            .HasMaxLen(FirstName, 40, "FirstName", "Name should have no more than 40 chars")
            .HasMinLen(LastName, 3, "FirstName", "Name should have at least 3 chars")
        );
    }
}

Now, we can use the Validate method and check if our command is Invalid, as shown below:

void Create(CreateCustomerCommand command)
{
    command.Validate();
    if (command.Invalid)
        return;
        
    var customer = new Customer(command.FirstName, command.LastName);
    var order = new Order(customer);
    // ...
}
You can’t perform that action at this time.