Daniel Hoelbling-Inzko talks about programming

Good ideas worth spreading: Guards

Posted by Daniel Hölbling on June 6, 2009

It’s amazing how much smarter you can become by simply looking at other people’s code. So, today I spent almost half the morning looking at different test frameworks from the TDD/BDD world looking for cool tricks I haven’t thought of (I examined MSpec, NBehave, NSpec and xUnit). One of those interesting little tricks (trivial at best, but valuable) is the following I found in xUnit’s Guard.cs:

Guard class, used for guard clauses and argument validation

Imagine the following method:

public bool Authenticate(string username, string password)
    return username == "daniel" && password == "tigraine";

Let’s say my specification for this method says: “input username and password can’t be null and should return a ArgumentNullException”. Reasonable, since we never trust input. So, usually I’d create guard clauses at the top of my method to protect me from said bad input:

public bool Authenticate(string username, string password)
    if (username == null)
        throw new ArgumentNullException(username);
    if (password == null)
        throw new ArgumentNullException(password);

    return username == "daniel" && password == "tigraine"; }

I always thought about this as rather readable and nice to work with, until I saw what xUnit did in Guard.cs, allowing me to shorten the above to a simple:

public bool Authenticate(string username, string password)
    Guard.ArgumentNotNull("username", username);
    Guard.ArgumentNotNull("password", password);

    return username == "daniel" && password == "tigraine"; }

I still believe this can be improved upon, maybe making it only one argument instead of two, but for now this is way better than what I used to write before.

Filed under net, programmierung
comments powered by Disqus

My Photography business


dynamic css for .NET