Code Contracts

On Monday, Microsoft released a preview version of Code Contracts, the design-by-contract feature that will be included in the .NET 4.0 Base Class Library. This appears to have been born out of the Spec# research project, but is available for all .NET languages, rather than being an extension of C#.

I’ve just been having a quick play, and it really is quite sweet, particularly the static code analysis that detects contract violations before the program is executed.

For example, here’s part of a repository class I wrote a few years ago, to return a collection of customers matching criteria defined in a query object. In time-honoured tradition, I validated the input parameters to my public method with guard-clauses, and threw exceptions as appropriate at runtime:

Now, in this brave new world of design-by-contract, we can rewrite those guard clauses more expressively as:

And, having enabled the static analysis and squiggly line options (via a new project properties pane), we get design-time warnings of contract violations:

I also like the way that automated testing tools such as Pex can make use of the contracts to generate more meaningful unit tests. Yet more grunt work we can offload onto the IDE :-)

There’s much more to it than this, and I encourage you to take a look at the site, and browse the documentation. It strikes me as being an excellent tool to help build bullet-proof class libraries, and I look forward to using it in earnest in .NET 4.0.