Sunday, October 4, 2009

Design by Contract and Containers classes

I had to write a special ordered linked list class for a project at work. Since I have seen a lot of example of applications of Design by contract for this type of code I decided to give it a try. For the DbC preconditions and postconditions I did not use anything fancy I just wrote a class with static methods that all look like this:


public static void precondition (string description, bool assertion)
{
#if DEBUG
if (!assertion)
{
throw new AssertionException (
"Precondition error: " + description);
}
#endif
}



When not running in debug mode the method becomes empty and if you decide not to put them in a conditional compilation block the overhead is very small. In my case because the ordered linked list is used in a very performance critical part of the program all use of the precondition and postcondition are in a #if DEBUG/#endif block. This clutters the code but considering the gains it is not so bad. (Microsoft has something available that is somewhat cleaner but when I last checked you needed the Team Edition of VS to use it).
Anyway, I found that for something like a container DbC is really great. Along with DbC I also wrote a good suite of unit tests for my class. Turns out the DbC checks detected a few errors in my code that would have gone undetected with my initial batch of tests. The DbC failure gave me a really good hint about the kind of tests I had to add so in the end with the DbC checks and the updated test suite I was really confident about my new class (I eventually got 80% coverage in my test and I plan to write the one or two missing tests I need to get to 100%). I felt that comming up with and writing the preconditions, postconditions and invariant really helped me quickly get to fully working solution.
I will not hesitate to use this again despite the clutter for any class I feel will benefit from DbC.

No comments:

Post a Comment