Monday, March 9, 2009

Code Contracts in C#

One of the new technologies Microsoft has coming down the pipeline for .NET 4 is Code Contracts. What are code contracts?

Code Contracts provide a language-agnostic way to express coding assumptions in .NET programs. The contracts take the form of preconditions, post-conditions, and object invariants. Contracts act as checked documentation of your external and internal APIs. The contracts are used to improve testing via runtime checking, enable static contract verification, and documentation generation.

But what they are is so much more, they bring design by contract to .NET. Traditionally one would set up some type of argument checking to verify the validity of what was passed in, and probably return some type of invalid argument exception upon failure, like the following:


public class DummyObject
{
public DummyObject(int n)
{
if(0 < n)
throw new InvalidArgumentException("n must be greater than 0.");
}
}


This isn’t the most elegant of solutions, also it is only verified at runtime. With Code Contracts, you now have static checking of your code conditions to see if you violated the contract at compile time. As far as testability this is great. But even better is that we as developers can tailor our code, to make the compiler a little bit smarter. In the code above everything would compile just fine if we initialized a new instance of our “DummyObject” with a 0, only when we ran it would we see an error. Now if we were to rewrite this with code contracts it would look like this:



public class DummyObject
{
public DummyObject(int n)
{
Contract.Requires(0 < n);
}
}


Now with static checking turned on we would see an error at compile time telling us that we have violated the contract. This is one of the simplest examples there is a great deal more that can be done. I recommend reading the Microsoft research site and look for other articles out there.

2 comments:

Anonymous said...

You're saying if 0 is less than n then throw an exception 'n must be greater than 0'.

I think you mean if n is less than 0 then throw the exception :p

Evan Freeman said...

Yes my code example has a typo. Ahh well.