CodeContracts – Amazing… simply amazing

Look at this code… looks perfectly normal right?  In a code review, you wouldn’t notice anything amiss.

 var tags = new List<DataCacheTagContract>();
tags.Add(new DataCacheTagContract() { Tag = "tag" });
tags.Add(new DataCacheTagContract()); 

Add("key", "value", TimeSpan.FromSeconds(1), tags);

But there is a bug present and it isn’t obvious…  How would you know?  Code Contracts saved the day.  When I ran the unit test that this code comes from I got a test failure.

 
Exception message: System.Diagnostics.Contracts.__ContractsRuntime+ContractException: Postcondition failed: Contract.Result<string>() != null

Strange I thought… I didn’t realize I had a contract on the DataCacheTagContract class but I do – it is an inherited contract and because I’ve installed a  VS2010 extension that the team is developing that shows me inherited contracts I can see what is going on.

DataCacheTagContract overrides ToString()

image

The CodeContracts extension shows me that I’ve inherited contracts because I’m overriding this method.  Do you realize how amazing this is?  I’m overriding a method and even though I don’t know the semantics of the method I’m overriding as well as I should, CodeContracts knows and applies them. 

I click on the Contracts inherited from Object text and it shows me that ToString() should never return null.

image

How many bugs exist in code because somebody overrides a method and silently breaks the semantic of the method by the way it was implemented.  With CodeContracts I can supply tools that will help them to know when they are doing this.  Wow – I never want to write code without CodeContracts ever again.