In the past I have written about the Fail Fast principle. This is a principle I try to live my development life by. I would rather explicitly check for possible failure points then have a runtime error crop up. In the past when writing these failure check we have had to resort to a few 'cavemanish' techniques. But with the inception of Extension Methods (here or here) we can actually create something that is pretty simple as well as elegant.
Lets take a look at a few examples where we are NOT using extension methods to accomplish our failure checking.
public bool SomeMethod( string key )
{
// In this case the key cannot be null or empty
if ( key.length == 0 ) { throw new ArgumentOutOfRangeException( "key", "Some Message Goes here" ); }
}
The code above works, it is pretty simple and will get the job done. But to be honest, having this sprinkled all over your code is kinda ugly.
public bool SomeMethod( SomeObject obj, Int32 someInt )
{
// In this case the object cannot be null
Assert.IsNotNull( obj, "Some Object" );
// In this case the int must be greater then 1
Assert.IsTrue( someInt > 1, "Some Int not correct" );
}
This code works as well and is more concise the the previous example. However, this code is still less readable then the example below.
Now, lets take a look at the same thing, but using Extension Methods
public bool SomeMethod( SomeObject obj, strnig someString )
{
// In this case the object cannot be null
obj.AssertNonNull();
// In this case the cannot be null or empty
someString.AssertNotNullOrEmpty();
}
Here is the code for the actual extension methods assert
public static void AssertNonNull( this T value )
{
// Do our null check here.
if ( value == null )
{
// Could even use reflection to gather info such as calling method, method exception was
// found in, etc.
throw new ArgumentNullException( "Some message here" );
}
}
The assert above using the extension method to me is the most elegant. It is easy to read (very important) and very concise.
Keep in mind, all the examples above do the exact same thing, but they do in varying levels of elegance. I would argue that the usage of extension methods here makes the code cleaner and easier to read.
Till next time,