Skip to content

04. Design By Contract

Andre Baltieri edited this page Jul 4, 2021 · 5 revisions

Design By Contracts

If you stop to look your code right now, I'm almost sure you will find things like these:

if(string.IsNullOrEmpty(myString))...
if(myBool)...
if(myDecimal <= 0)...

This happens very often, and everytime you put a condition in your code, basically you will need one more test, this is why they bring so much complexity to our lifes.

I'm not telling you'll not use IF anymore, but that we can pick these simple validations and put it in some methods, test it and re-use it!

In Flunt we shipped a lot of common validations, testeds and ready to use, integrated with our notifications lib. And as we're open source, even more validations are comming every day.

You can check the complete list of validations on Validations Wiki

Creating Contracts

We can create contracts using Contract class, and combine it with AddNotifications method, to create a contract and add use it at same time, as show below:

public Customer(string firstName, string lastName)
{
    AddNotifications(new Contract()
        .IsLowerThan(firstName, 40, "FirstName", "Name should have no more than 40 chars")
        .IsGreaterThan(firstName, 3, "FirstName", "Name should have at least 3 chars")
    );
}

Here is another example, using Contract, AddNotifications and Valid:

public void ChangeCustomerName(string firstName)
{
    AddNotifications(new Contract()
        .IsLowerThan(firstName, 40, "FirstName", "Name should have no more than 40 chars")
        .IsGreaterThan(firstName, 3, "FirstName", "Name should have at least 3 chars")
    );

    if (Valid)
        FirstName = firstName;
}

Concatenating Contracts

We can concatenate contracts by just call Join method from one contract:

new Contract()
    .IsLowerThan(firstName, 40, "FirstName", "Name should have no more than 40 chars")
    .IsGreaterThan(firstName, 3, "FirstName", "Name should have at least 3 chars")
    .Join(otherContract, oneMoreContract, someOtherContract);

Flunt

Clone this wiki locally