2 min read

Using Guard Clauses in .NET

I would certainly recommend using this library - it's convenient and improves the quality of your code.

If you've written a bunch of code that looks like this:

public void ProcessOrder(Order order)
{
	if (order == null)
	{
		throw new ArgumentNullException(nameof(order));
	}
	// process order here
}

Then you probably have a few different checks that follow as well (perhaps range checks, etc). It is obviously good coding practice and absolutely essential to robust programming, but it tends to make the code look busier. Since you can't get away from this (if you're leaving it out that's a whole other topic for discussion), you can definitely benefit from the Ardalis.GuardClauses package:

ardalis/GuardClauses
A simple package with guard clause extensions. Contribute to ardalis/GuardClauses development by creating an account on GitHub.
Ardalis.GuardClauses 1.4.2
A simple package with guard clause helper methods. See docs for how to extend using your own extension methods.

It's README offers the following usage sample (equivalent of the above):

public void ProcessOrder(Order order)
{
	Guard.Against.Null(order, nameof(order));

	// process order here
}

For me, the most appealing part was that it is compatible with .NET 4 and I was working on a legacy project with an unknown upgrade path.

Initial reactions are that the library definitely proves useful, and simultaneously expressive and lean. It definitely reduces the code "noise" that might appear in the setup function, and I can see it encouraging better coding practices by condensing the call and making it more convenient to add the checks.

I would certainly recommend using this library - it's convenient and improves the quality of your code.