Home > Code Contract, dotnet 4 > Code Contracts

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.

Code contract tab in Visual Studio

Step 3

Lets gets started with writing some code

using System;
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.

Test Build

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

Test Failed

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;
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.

Code contract reports a warning
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.

Advertisements
  1. Kitpolte
    September 7, 2010 at 6:34 am

    Can you describe more on how to use it in a project ? Thanks

  2. Gorang
    September 22, 2010 at 6:21 am

    Cool thing. Enjoyed reading it

  1. September 1, 2010 at 12:01 pm
  2. September 21, 2010 at 9:45 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: