XAF has a new guard, and we’re not talking Kobe Bryant either! Nope, we’re talking about the new Guard class coming in XAF 9.3, a class to help enforce code contracts.
So how does it work? Well just look at this piece of code:
public void MyMethod(object myObject, string message)
{
if (myObject.GetType() != typeof(MyType))
{
throw new ArgumentException();
}
if (myObject == null)
{
throw new ArgumentNullException();
}
else
{
//...custom logic here
if (!string.IsNullOrEmpty(message))
{
//...custom logic here
}
}
}
Checking the arguments throughout the method body like this isn’t best practice, it clutters the method and makes the important business logic less visible. Now, contrast that with what the same method could look like using the forthcoming Guard class:
public void MyMethod(object myObject, string message)
{
Guard.ArgumentNotNull(myObject, "myObject");
Guard.ArgumentNotNull(message, "message");
Guard.ArgumentIs(typeof(MyType), myObject, "myObject");
//...custom logic here
}
This version makes the code much more readable and, to a certain extend, self documenting. The following table shows the other methods that will be available in the Guard class:
That’s it for this post, but keep an eye out for the other sneak peak posts from DevEpress’ evangelists.