Skip to content

05. Fail Fast Validations

Andre Baltieri edited this page Jul 4, 2021 · 5 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 interface IValidatable 
{
    void Validate();
}

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

    public void Validate()
    {
        AddNotifications(new Contract()
            .IsLowerThan(FirstName, 40, "FirstName", "Name should have no more than 40 chars")
            .IsGreaterThan(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);
    // ...
}

Flunt

Clone this wiki locally