DesignByContract with Fluent Interfaces
I was reading through some blog posts and through a recent post, stumbled across this one from Bill McCafferty and took a look at the DesignByContract CodeProject article. This is just a simple utility class to pass in assertions and get an exception to be thrown with a message if the contract has been violated. I did this manually in my last project using repetitive code that got to be a pain. On a new project I definately wanted to use a utility to perform these checks for me. The DesignByContract sample would seem to fit the solution. It is working fine thus far, but I didn’t like how the method calls looked and thought it would be a prime candidate for some fluent interfaces.
Here is my shabby attempt at a DesignByContract class to perform checks with fluent interfaces. Now instead of this:
Check.Require(!string.IsNullOrEmpty(username), “username is required”);
we can have this:
// with strings
Check.Parameter(username).WithMessage(“username is required”).IsNotNullOrEmpty();
// with objects
Check.Parameter(someObject).WithMessage(“some object is required”).IsNotNull();
A little longer to type, but with ReSharper who really types out whole method names anymore =) Theres probably a better way to do it with generics but for the time being I just needed to make sure that parameters were not null. So all this class does is check for null/not null. In the near future I will add assertion checks in there as well. I haven’t had a need for that yet and why write unnecessary code!
You can get the DesignByContract.cs and tests from my Google Source code repository here:
http://schambers.googlecode.com/svn/FluentDBC/
If anyone has any additions please send me a patch and I will be happy to add it!