Thursday, April 7, 2011

Guard your code

You can call it code contracts or an argument guard. This is a simple implementation that can validate that the current state of a variable or method is as you expect it to be. If the validation fails, an exception is thrown. Example code:
public void SomeMethod(int arg1, int arg2)
{
    // This line will throw an exception when the arg1 is less or equal to arg2
    Guard.Check(() => arg1).IsGreaterThan(arg2);

    // This will check that arg1 is not null and that is in some range 1..100
    Guard.Check(arg2).IsNotNull().IsInRange(1,100);

    // Do stuff
}
Source code can be found on GitHub
Share: