Skip to content

FluentContracts/FluentContracts

Repository files navigation

Logo

FluentContracts

NuGet Version NuGet Downloads

API for defining argument validation contracts in a fluent manner.

Inspired by FluentAssertions

Why another validation library

I am perfectly aware of the other libraries out there, that are doing the same stuff.

Libraries like FluentValidation and Guard from .NET Community Toolkit are awesome and have tons of functionality, support and experience. If you like those and use them already, that is fine.

I did this one, because I don't really like how the other libraries require you to write, in order to achieve the validation. It is pretty verbose for my taste. I wanted to make something more simple and "human-readable", the same way FluentAssertions does it for unit testing.

Usage

The usage of the contracts is pretty simple. You can use the extension methods everywhere you want to do a validation of some variable.

Generally when we write methods, constructors, etc., we do validation like that:

public void AddOrder(Order myOrder)
{
    if (myOrder == null) throw new ArgumentNullException(nameof(myOrder));    
    if (myOrder.Quantity < 5) throw new OrderQuantityException("Order quantity cannot be less than 5");
    
    ...
}

With FluentContracts your code will look like this:

public void AddOrder(Order myOrder)
{
    myOrder
        .Must()
        .NotBeNull()
        .And
        .Satisfy<OrderQuantityException>(
            o => o.Quantity >= 5, 
            "Order quantity cannot be less than 5");
    
    ...
}

or as simple as:

public int Divide(int a, int b)
{
    b.Must().NotBe(0);    
    return a / b;
}

User defined exceptions

You can also throw your own exception like that:

public void AddOrder(Order myOrder)
{
    myOrder.Must().NotBeNull<OrderNullException>();
}

This will throw an instance of OrderNullException if myOrder is null.

Supported contracts

You can find them HERE.

Help needed πŸ™

My goal for this project is to become as exhaustive, safe and stable as possible, so people can use it in production and on big projects. So I need some help. If you are interested in helping out just send a pull request, open an issue, etc.

Repository 🚧

Builds

Type Status
Dev Build Dev Linux
Dev Build Dev Windows
Dev Build Dev MacOS
Code Coverage Coveralls
Release Release

Status

Alt

How to build locally

  • Clone repos
  • Run build.cmd

Where to find me πŸ•΅οΈ

Blog X LinkedIn Mastodon Threads BlueSky Linktree Email

Special thanks πŸ™‡β€β™‚οΈ

The creator of NUKE, because I cannot build any .NET project without it and because he helped me tremendously in setting up the repository and everything around this project. (I have also copy-pasted, like his entire build and some markdown files 🀫)

The "FluentAssertions" guy. This whole project was inspired by how that library works and I might have copy-pasted also parts of his repo too 😏

Icon made by IconMonk from Flaticon