This post proposes a standard way to implement and call method parameter validation logic.
Instead of writing out the method parameter validation code in each method over and over again we will centralize it in a static helper class. This static helper class will be reusable over different projects and will speed up writing method parameter validation code.
This is the way most of us write method parameter validation code:
public void MyPublicMethod(string name)
{
if(String.IsNullOrEmpty(name))
{
throw new ArgumentNullException("name");
}
// method impl...
}
public void MyPublicMethod(string name)
{
Throw.IfArgumentNullOrEmpty(name, "name");
// method impl...
}
With a central place to write parameter validation code you can make it a little more elaborate than you would if you'd had to write it in each method seperately. Notice the implementation make a distinction between is null and is empty.
public static void IfArgumentNullOrEmpty(
string argument, string argumentName)
{
if (String.IsNullOrEmpty(argument))
{
IfArgumentNull(argument, argumentName);
throw new ArgumentException("Argument cannot be empty.", argumentName);
}
}
There is one drawback in using this method of performing method parameter validation. FxCop does not recognize that you are performing validation on these parameters and will insist that you do. I hope that the FxCop (Code Analysis) team at Microsoft will come up with a code attribute we can use to decorate our "method parameter validation" methods.
You'll notice this way of implementing validation logic does not work well with The Throw Method. I personally think that method parameter validation exceptions require less or no context information other than perhaps the parameter value itself.