How mature is the Microsoft Code Contracts framework?

The last mature response to this was in 2009, and .NET 4 is out. I figure we’re due for an update:

Code Contracts might well be mature enough for your Debug releases.

I realise this is somewhat of an upgrade from “Harmless” to “Mostly Harmless”.

The Code Contracts home page links to quite thorough documentation in PDF format. The documentation outlines usage guidelines in section 5. To summarize, you can pick how brave you feel about the Contract Tools re-writing your IL in your Release builds.

We’re using the “don’t rewrite my Release IL” mode.

So far, I’m most enjoying this unexpected benefit: there’s less code, thus less code to test. All your guard clauses melt away.

if(arg != null) { 
    throw new ArgumentNullException("arg"); 
}
// Blank line here insisted upon by StyleCop

becomes:

Contract.Requires(arg != null);

Your functions are shorter. Your intent is clearer. And, you no longer have to write a test named ArgumentShouldNotBeNull just to reach 100% coverage.

So far, I’ve run into two problems:

  • I had a unit test which relied on a contract failure to succeed. You might argue the existence of the test was a blunder, but I wanted to document this particular prohibition in the form of a test. The test failed on my build server because I didn’t have the tools installed. Solution: install the tools.

  • We’re using two tools that rewrite IL: Code Contracts and PostSharp. They didn’t get along too well. PostSharp’s 2.0.8.1283 fixed the problem. I’d cautiously evaluate how any two IL-rewriting tools get along, though.

So far, the benefits are outweighing the hazards.

Addressing out-of-date concerns raised in other answers:

  • Code Contracts’s documentation is quite thorough, though regrettably in PDF.
  • There’s at least one Code Contract forum hosted by Microsoft.
  • Code Contracts Standard Edition is free if you have any VS2010 license.
  • .NET 4 is out. I’ve run into Microsoft’s contracts when implementing generic collection interfaces.

Leave a Comment