OdeToCode IC Logo

Argument Validation

Sunday, February 6, 2005

I’m still poking around the common validation areas of Enterprise Library.

The ArgumentValidation class has 6 public static methods:

public static void CheckForEmptyString(string variable, string variableName) ...
public static void CheckForNullReference(object variable, string variableName) ...
public static void CheckForInvalidNullNameReference(string name, string) ...
public static void CheckForZeroBytes(byte[] bytes, string variableName) ...
public static void CheckExpectedType(object variable, Type type) ...
public static void CheckEnumeration(Type enumType, object variable, string) ... 

CheckForEmpty string has the following implementation:

   21 public static void CheckForEmptyString(string variable, string variableName)

   22 {

   23    CheckForNullReference(variable, variableName);

   24    CheckForNullReference(variableName, "variableName");

   25    if (variable.Length == 0)

   26    {

   27         throw new ArgumentException(SR.ExceptionEmptyString(variableName));

   28    }

   29 }

I like this approach to validation. It feels much cleaner to start a method off with a handful of static method calls to validate arguments compared to starting with a handful of conditional blocks sprinkled with throw statements. The checks are explicit and readable here.

I know some people go nuts defining custom exception hierarchies – I’ve never been a big fan of that approach. The EntLib uses exception classes from the BCL, and keeps the error messages in a resource file and ready for localization. Clean. Flexible.

Most checks are in the form of if (variable == null), although there is at least one place where the code looks like: if (null == variable). I understand the reasons why we did this in C++: it was easy to mix up the assignment operator with the equality operator, but I never cared for expressions in this form and never subscribed to the practice. The C# compilers are better at warning about this subtle error, so I don't plan on ever switching either.

Next up: unit tests in EntLib. I might be looking these over during the trek to VSLive! tomorrow.

Mike Lorengo Sunday, February 6, 2005
This reminds me of an article I read on the Code project. Nils Jonsson created a utility library (along with the Unit Tests) that does some very similar things. http://www.codeproject.com/csharp/ArgumentExceptions.asp
Raymond Lewallen Monday, February 7, 2005
Yeah, my code is still littered with individual checks with throws in each method that requires them. I've been wanting to implement the same pattern the EntLib is using for about a year now, but other things have been taking priority. Its a great design and I hope to get a bunch of code converted in the next 6 months.
Comments are closed.