This is part of a series of articles covering not only the technical capabilities of .NET Code Contracts being added in v4.0 of the .NET Framework, but also the benefits of this technology and how developers can leverage the technology in their projects.
What is Code Contracts?
Code Contracts is a direct descendant of the Spec# project – which was a research project designed to add design-by-contract functionality to the C# language. While its syntax was quite similar to Eiffel (which was the first to implement DbC), it was always intended to be a research project. Most of the team moved over to work on Code Contracts, which applied this knowledge with the goal of providing better integration with the .NET Framework and tooling support within Visual Studio.
The Base Class Library team is using Code Contracts to verify the core libraries of .NET 4.0 as it heads towards being released next year – with the longer-term goal being that contracts can be used as first-class citizens by third party developers building applications and components on top of .NET. These contracts are included when you download the Code Contracts tools, so you can see how the BCL team is using Code Contracts.
What is Design By Contract?
For those who are unfamiliar with design-by-contract, its a pattern for specifying how components in an application behave. I’ll defer to Wikipedia here, because I think this is the best summary out there about the focus of design-by-contract:
What does it expect?
What does it guarantee?
What does it maintain?
You’re probably rolling your eyes at this point, so lets stop handwaving and use a practical example. I’ll drill down a bit deeper on the concept itself in another entry, but this should be a good starting point.
A Tale of Consumers and Suppliers
In a typical contract, there are two participants – for simplicity’s sake, we’ll call these entities the consumer and the supplier. In the real world, the supplier would be the developer writing the component, and the consumer could be a different developer using the component in their application.
Say I have implemented a collection, and this is the method for adding an item:
public void Add(T item)
{
if (item == null)
throw new ArgumentException("item");
// ... add the item to a collection
}
public int Count
{
get {
// implementation
}
set {
// implementation
}
}
For this method above, we have an implied expectation that the consumer will provide a non-null item as the parameter. The method will throw an exception otherwise, to scold the consumer about doing something silly.
How can the consumer understand this requirement when writing code against this class?
Personally, I’d suggest Reflector here (a godsend and should be in every .NET developer’s toolset), but that’s hardly ideal to do for every class and library you deal with. In a utopian developer society, we should be able to find this information easily and quickly.
There is also a guarantee here – can you spot it? Think about what is being managed internally by the collection and is being exposed to the consumer.
There is a guarantee around the behaviour of the Count variable – the supplier must ensure that the Count value is updated when Add is finished. Should we take it for granted that this will be incremented?
How can we verify that Count is correct at the end of the Add method?
This depends on the implementation of the collection. You could write a unit test to achieve this, but we can specify this as part of the contract, and use the static checking tools to verify the behaviour.
What does a contract look like?
This depends on the implementation of the language - Eiffel has DbC available natively, other languages have contract available via third party libraries – and .NET 4 will have Code Contracts built into the core. How these contracts are integrated into assemblies will be discussed in a later entry.
So, to rewrite the above section to use Code Contracts, this is how it would behave:
using System.Diagnostics.Contracts;
// ...
public void Add(T item)
{
Contract.Requires(item != null);
Contract.Ensures(Contract.OldValue(Count) + 1 == Count);
// ... add the item to a collection
}
public int Count { get; set; }
So we’ve taken out the exception and included two statements which form the contract:
The expectation of the consumer: I require that ‘item’ is not null.
The guarantee of the supplier: I ensure that ‘Count’ will be incremented by this method.
There are other contract statements available (Assert and Assume) but these are only verified at runtime – rather than the all-round awesomeness of static verification.
How does this work in Visual Studio?
Code Contracts are not available by default in Visual Studio. You need to install the tools from the project site to get the integration – this is available for 2008 or 2010. Not sure on whether this is going to be something that will be available
This is how I’ve set up my project. There’s a fair bit of control over what can be tested here.
Sidenote: There are two versions of Code Contracts – Standard and VSTS Edition. The only difference between the two is that the Static Checking is available with VSTS – which I think is the most important feature in terms of supporting design-by-contract. Insert sadface here. Guess its going to become like FxCop – a nice tool available and used by the percentage of the community who already do this sort of thing. Oh well. Back to regular transmission.
Having all that set up, I create an instance of my custom collection and try to add null to it (because I’m silly and trying to make a point). No compilation errors are raised, but I get a harsh warning message.
So I have two choices here: ignore the warning or fix it. Of course, I’m trying to make a point here, so I’m going to ignore it. Pressing F5 runs the app, but then I ...
Oh crap, that’s a lot of stack trace. I’ve highlighted the stack which is managed by Code Contracts, but this also gives us the option to debug the code.
The error that I ignored. Well, I guess I should fix it because the user’s not going to like that message either.

And the verification passes. Sweet.
If the shoe was on the other foot, and the supplier was at fault, you’d see a similar scenario.
|
|
|
Oh! That's what that line was supposed to do!
|
The Summary (people who have a short attention span, read this)
Code Contracts is a feature that will be available in .NET 4.0 that will allow developers to specify contracts in their code, which are exposed when the library is used by a third party. The tooling in Visual Studio is progressing along nicely (with enough guidance to help resolve issues without getting in the way) but the restriction on the static checking tools is something that will prevent many from utilizing Code Contracts to its fullest.
With the ongoing evangelism of practices to improve software development, I hope that this becomes another tool in the belt for good developers to build quality code – it is a different pattern to TDD, but I believe they can work side-by-side. It will be interested to see how this gets picked up by the community as .NET 4.0 heads towards going gold in March.