Home > Code Contract, dotnet 4 > Deep dive into Code Contracts

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

  1. Pre conditions
  2. Post conditions
  3. Assertion
  4. Object invariants

This is the code I used it in my previous post

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 …
        }
    }
}

Let’s see each type one by one.

1. Pre Condition

Lets apply the Pre Conditions to this code and rewrite as

  public class ProductRepository
  {
     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..

public Product Process(Product product)
{
    product.Description = null;
    return product;
}

 

And add an overload to our AddProduct method which calls the Process method

public  void AddProduct(Product product)
{
    Product p = Process(product);
}
       

Lets write a test.

[TestMethod]
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.

public void AddProduct(Product product)
{
     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.

Post condition

3. Assertion

This one is pretty straight forward as the name says you are asserting a value to be checked.

public void AssertProduct(int id)

   Contract.Assert(id == 10,"Product id must be 10");
}

and the test would be

[TestMethod]
public void TestAssertCondition()
{
   var dc = new ProductRepository();
   dc.AssertProduct(20);
}


post condition

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 class Product
{
   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

[TestMethod]
public void TestInvariantCondition()
{
   Product p = new Product();
   p.Id = -10;
}

Invariant Method

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.

Advertisements
  1. Gorang
    September 22, 2010 at 6:22 am

    Nice one.

  2. September 22, 2010 at 11:19 pm

    Gorang :

    Nice one.

    Thanks Gorang,
    Keep your comments coming in and let me know if there is any specific area you want to see in the future 🙂

  3. watch movies online
    October 16, 2010 at 7:10 pm

    Fantastic web site, I hadn’t noticed prashantbrall.wordpress.com before in my searches!
    Continue the good work!

    • October 18, 2010 at 6:10 am

      Thanks a lot. I just started as reference point for myself but good to know that my project experiences are helpful to others.

      Enjoy !!

  4. corChazycrync
    December 7, 2010 at 8:51 am

    Hi, very interesting post, greetings from Greece!

  1. No trackbacks yet.

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: