Archive
Deep dive into Code Contracts
A couple of weeks ago i did an introduction of code contracts in which I showed you that it is part of the new System.Diagnostics.Contracts namespace but the static checking is not part of .NET 4.0 and to get it please refer to my past post.
If we look into the code contract there are mainly 4 types of code contracts
- Pre conditions
- Post conditions
- Assertion
- Object invariants
This is the code I used it in my previous post
using System.Diagnostics.Contracts;
namespace CodeContract
{
public class ProductRepository
{
public void AddProduct(Int32 productId,string description)
{
if (productId <= 0)
{
throw new ArgumentException();
//return;
}
Contract.EndContractBlock();
//… Rest of the implementation …
}
}
}
Let’s see each type one by one.
1. Pre Condition
Lets apply the Pre Conditions to this code and rewrite as
{
public void AddProduct(Int32 productId,string description)
{
Contract.Requires(productId > 0); // Pre condition
}
}
and if run the test with a negative productId we get a warning saying that the id must be greater than 0.
2. Post Condition
Lets write another method which assigns null to the description..
{
product.Description = null;
return product;
}
And add an overload to our AddProduct method which calls the Process method
{
Product p = Process(product);
}
Lets write a test.
public void TestPostCondition(
{
var dc = new ProductRepository();
var p = new Product() { Id = 500};
dc.AddProduct(p);
}
It is evident that when we compile this there are no errors or warnings but we know that if we rely on that the method which might return a null string then it would be disastrous.And it order to stop this from happening we will add a post condition contract i.e. after the processing makes sure the description is not null.
{
Product p = Process(product);
Contract.Ensures(!string.IsNullOrEmpty(p.Description)); // Post Condition
}
And now when we compile our test project we get a warning as the Ensures method of Contract class makes sure that after the method call the value is not null.

3. Assertion
This one is pretty straight forward as the name says you are asserting a value to be checked.
{
Contract.Assert(id == 10,"Product id must be 10");
}
and the test would be
public void TestAssertCondition()
{
var dc = new ProductRepository();
dc.AssertProduct(20);
}

4. Contract Invariant Method
Contract Invariant can be decorated to a parameter less void method and it’s more to do with the state of an object. In order to use it I am going to rewrite the Product class as following.
{
public int Id { get; set; }
public string Description { get; set; }
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(Id >= 0);
}
Lets write a test to set the value as negative like this
public void TestInvariantCondition()
{
Product p = new Product();
p.Id = -10;
}

I get a squiggly right under the assignment line and get the following warning.
So these are the 4 different type of code contracts and I am hopeful that with these examples it will make you think where best you can use in your project. If you are wondering what’s happening behind the scene then look for binary rewriter i.e. ccrewrite.exe as this is the tool which discovers these contract and rewrites your program with these assertions.
Code Contracts
I am always up for a new ideas and experimenting new stuff and one of the cool stuff I always read in “What’s new in .net 4.0” is the code contract. I mean it definitely sounds familiar as WCF have various forms of contracts, interfaces are contracts etc.
I started digging a bit into it and found out that it sits inside the “System.Diagnostics.Contract” assembly and that give me a clear direction where was this heading. For me I wanted to check out how much of code checking it can do before we execute the code.
But like most of the new and cool stuff they are not that easy for the first time and there are a lot of gotchas and hoops you have to go through before you can start using it.
So here is my set of steps to get started with it.
Step 1:
Download it from here. The first gotchas was here itself for “Static Checking” download the Premium Edition and for that you must have Visual Studio 2008 Team System, Visual Studio 2010 Premium Edition or Visual Studio 2010 Ultimate Edition.
Step 2
Start Visual Studio go to project properties and make sure you have the “Code Contracts” as the new tab in the properties.

Step 3
Lets gets started with writing some code
using System.Diagnostics.Contracts;
namespace CodeContract
{
public class ProductRepository
{
public void AddProduct(Int32 productId,string description)
{
if (productId <= 0)
{
throw new ArgumentException();
}
//… Rest of the implementation …
}
}
}
and write a simple test for the add method.
[TestMethod]
public void Test()
{
var dc = new ProductRepository();
dc.AddProduct(10, "Chai");
}
Now when we build the test and run it there are no surprises and the test passes with flying(green) colours.

Lets say instead of passing a positive values we pass a negative one and as expected the test failed and got our exception.

I am glad that we wrote the test and it was caught before the code went into the production but wish if there was some tool which could tell me about this exception even before I could execute the code. Sounds crazy isn’t it ? ( reminds me of Minority Report
where the perpetrators are caught before they have committed the crime ).
No the idea is not that crazy and lets see how we can use Code contract to anticipate these type of code pitfalls.
Go to the Static Checking section and check the following checkboxes
- Perform Static Contraqct Checking
- Check in Background
- Show squigglies
and in Runtime Checking check the “Perform Runtime Contract Checking”. now we will add a bit of magic into our “Add Product” method ..
using System.Diagnostics.Contracts;
namespace CodeContract
{
public class ProductRepository
{
public void AddProduct(Int32 productId,string description)
{
if (productId <= 0)
{
throw new ArgumentException();
//return;
}
Contract.EndContractBlock();
//… Rest of the implementation …
}
}
}
All we have done is just added one method “EndContractBlock()” of the Contract class right after out exception and lets built the test project.

And this is pure magic. The Code contract reports a warning since we are violating the value of the passed parameter with a blue squiggly as we turned that option on.
As you can this is just a tip of the iceberg and imagine what you can achieve when you started define these contracts using annotation and decorating your classes with it, this will definitely make your API/library and your testing more robust.
The other area where I see a lot of use could be of a legacy .NET app which doesn’t have good unit test or any test at all, you can assert these contract block to identify various defects in the legacy .NET app.