NValidate

A couple of years ago I discovered something called Design By Contract while reading The Pragmatic Programmer. I LOVED the way DBC worked. Unfortunately DBC doesn't have native support in .NET. There was a class written that is available on code project that I used it on a couple of projects and it worked well.

However during my current project while writing some tests I decided to take a look at what else there is out there. Nothing new on the DBC front but a nice lightweight framework to validate method parameters was discovered. The open source project is called NValidate. What's nice about this framework is it's ability to stack parameter checks into a single line of code. For instance if I wanted to check that a parameter with a type of "String" is not null or empty and does not have a length greater than 50 it would look something like this without nvalidate:

If stringParameter.IsNullOrEmpty() then
     Throw New ArgumentException("stringParameter is null or empty.")
End If

If stringParameter.Length > 50 Then
     Throw New ArgumentException("stringParameter cannot be more than 50 characters long.")
End If

With NValidate it looks like this:

Demand.That(stringParameter, "stringParameter").IsNotNullOrEmpty().HasLengthOfNoLongerThan(50)
Note: Because this is an open source project I was able to add the HasLengthOfNoLongerThan method. This method is not in the framework that is downloaded.

"That" is an overloaded method has an implementation for each type of validator in the NValidate project. Some of those validators are BooleanValidator, DateTimeValidator and Int32Validator.

If you don't want to write endless if...than statements take a look at the NValidate project. If there something that that it doesn't support add what you need to it.

 FYI: My LINQ TO SQL Dynamic Query using OR statements post is coming up next. Sorry for the delay.

Technorati Tags:   

posted @ Wednesday, February 13, 2008 2:12 PM

Print

Comments on this entry:

# re: NValidate

Left by Christian Crowhurst at 5/11/2008 3:38 PM
Gravatar
Hi Chris,
Have you thought about combining the NValidate with that little Dbc framework from codeproject?

Here's an example that wraps the argument exception thrown by NValidate in a pre-condition exception:

object o = null;
Check.Require(delegate {
Demand.That(o).IsNotNull();
});

# re: NValidate

Left by Christian Crowhurst at 5/11/2008 3:38 PM
Gravatar
Hi Chris,
Have you thought about combining the NValidate with that little Dbc framework from codeproject?

Here's an example that wraps the argument exception thrown by NValidate in a pre-condition exception:

object o = null;
Check.Require(delegate {
Demand.That(o).IsNotNull();
});

Your comment:



 (will not be displayed)


 
 
 
Please add 7 and 4 and type the answer here:
 

Live Comment Preview:

 
«March»
SunMonTueWedThuFriSat
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910