Sunday, February 05, 2006

Precondition checks

In my code I always try to do at least basic validation of method arguments against method preconditions. What I mean here is checking for invalid null arguments, empty strings, not-negative numbers, etc. I do it for two reasons:
  1. It clearly comuniacates what assumptions were made about the arguments when coding the method.
  2. It can save some debugging time when the method doesn't do what it should only because the arguments were not what you expected them to be.
The code I used to write looked like this:

public void Foo(object item)
{
if (item == null)
throw new ArgumentNullException("item");

...
}

The code above works fine, but does it really communicate CLEARLY what my intension was. To me, every if statement makes the code less readable so to make my intensions more clear I could try to change it to:

...
// Precondition: item cannot be null
if (item == null)
throw new ArgumentNullException("item");
...

Did it get any better? Nope. I have just added a comment that says exactly the same thing as the code below it. Waste of space...
At some point I figured out that what I try to do here is exactly the same as what I do when writting unit tests. And when I write them I don't write:

if (result != 10)
Assert.Failed("Result is not equal to expected value.");

I write

Assert.AreEqual(10, result);

So this is my precondition checking code:

public void Foo(object item)
{
Precondition.ArgumentNotNull(item, "item");
...
}

The other methods I created to check for preconditions are for example:

Precondition.ArgumentNotEmpty(string value, string argumentName)
Precondition.ArgumentNotNegative(int value, string argumentName)
Precondition.ArgumentInRange(int value, int min, int max, string argumentName)
etc...

What do you think? Do you like it and think it makes some sense? Let me know :)

No comments: