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.