Thursday, October 21, 2010

Code Contracts

I recently downloaded Code Contracts from Microsoft. I got introduced to Code Contracts in Pragmatic Programmer and then got a better understanding of it from Jon Skeet's C# In Depth while the chapter was freely available (unfortunately, it is not now.) Code Contracts is another tool which should have been here a long while ago in .net world.

In Code Contracts, Preconditions are specified using Contract.Requires to specify constraints on the input to a method. Postconditions are used to specify express constraints on the output of a method using Contract.Ensures. Here is a code snippet from C# in Depth, Chapter 15, which shows code contract in action

static int CountWhitespace(string text) 

    Contract.Requires(text != null, "text"); 
    Contract.Ensures(Contract.Result() >= 0); 
    return text.Count(char.IsWhiteSpace); 
}

No comments: