Refactoring Guard Clauses

Kane picture Kane · Oct 21, 2009 · Viewed 16.9k times · Source

What approaches do people take (if any) in managing guard clause explosion in your classes? For example:

public void SomeMethod<T>(string var1, IEnumerable<T> items, int count)
{
    if (string.IsNullOrEmpty(var1))
    {
        throw new ArgumentNullException("var1");
    }

    if (items == null)
    {
        throw new ArgumentNullException("items");
    }

    if (count < 1)
    {
        throw new ArgumentOutOfRangeException("count");
    }

    ... etc ....
}

In the project that I am currently working on there are many classes that have a similar set of guard clauses on the public methods.

I am aware of the .NET 4.0 Code Contracts however this is not an option for our team at the moment.

Answer

David Brown picture David Brown · Oct 21, 2009

A lot of projects that I've seen use a static Guard class.

public static class Guard {
    public static void ArgumentIsNotNull(object value, string argument) {
        if (value == null)
            throw new ArgumentNullException(argument);
    }
}

It makes the code a lot cleaner, in my opinion.

Guard.ArgumentIsNotNull(arg1, "arg1");