Home > Development > Code Contracts – The Future?

Code Contracts – The Future?

Design By Contract comes to .Net

‘Design By Contract’ (DBC) is something the Pragmatic Programmers are very keen on.  Introduced as part of the Eiffel language some years ago, it’s a way of specifying how your classes and methods are used in more detail than you get by simple type-checking.

For example, say you had a method that divided some numbers:


The fact that your inputs are Integers means they can only contain certain values, but in this case if ‘Divisor’ contained zero, you’d have a DivideByZeroException on your hands.  A contract would enable you to specify that ‘Devisor’ must be positive, or could not be zero.  A more common example might be to ensure that an object passed as a parameter was not null.

You can also specify requirements on the return values from methods, or on objects as a whole – ‘whenever this object is in existence, the Foo parameter will not be null’, that kind of thing.  By doing this, you’re specifying a contract with users of your code: ‘If you ensure my method is called with the correct parameter values, I’ll guarantee that the return value will be within the specified range’.

This has never been much of a concern to most .Net developers, because although there are some libraries available that implement a kind of DBC for .Net, they are somewhat limited because they’re not part of the language, and certainly not widely used.  Generally, people wanting to implement a simple form of this type of checking would do so with exceptions or assertions:


But that’s all about to change!  As of .Net 4.0, currently in Beta 2, DBC will be officially part of .Net, under the name Code Contracts.  In fact Code Contracts is available now for VS2008 / .Net 3.5 if you want to get started with it straight away.  Originally called Spec#, this has been a Microsoft Research project for a while but previously only worked with C#.  Now it’s been fully productionized and added into mscorlib, with additional tools for compilation and static checking, and it’s all integrated into Visual Studio.

So now if we wanted to do the above check, we’d need to add a reference to Microsoft.Contracts (if we’re using vs2008), put a using in for System.Diagnostics.Contracts, and add the following code:


‘Wow’, I hear you mutter sarcastically, ‘you’ve replaced an Exception with some slightly different code..’.  But there’s more to it than that – for a start, as well as checking parameters, you can specify what a method’s output will be using a contract, and you can also specify that an object of a class will always be in a certain state:


As well as the Contract.Requires() which specifies the valid parameter states, you can see Contract.Ensures() which defines the valid return value of a method, and the method marked with [ContractInvariantMethod] which states that an object of the class must always be in that state.  The checks here are pretty basic – you could, for example, check that all of the data items in the return list were valid – but hopefully you get the idea.

So what happens when one of these checks fails?  By default, you get an assertion failure, but you can also get a ContractException, or even define your own custom behaviour.  You also have the choice of whether the checks should be performed only during development or for the release build.  As you can see from the Project Properties screen in Visual Studio, there are a fair few options:

Code Contracts Options

Code Contracts project options in Visual Studio

You might have noticed in the screenshot some options for static checking.   The static checker is a clever tool which actually analyses your code during compilation and gives you warnings if it can see something that doesn’t meet the specified contracts.  For example, if I tried to call my DataGenerator with an invalid parameter of zero:


I would get the following warnings that a contract check was going to fail, including the location of the problem and the contract check:

Code Contracts Compilation Warning

Code Contracts Compilation Warning

Good stuff!  Although from what I understand, this only works well if you’re very thorough and put contract checks on everything, as validating the code statically like this is a very difficult computing problem.

A few other interesting things that Code Contracts does, which you mainly can’t do with exception-style checking:

  • Contracts for interfaces
  • Contracts inherited from base classes
  • Code Snippets for common situations (e.g. Requires(!String.IsNullOrEmpty())

Aside from the obvious fact that you will find problems with your code more immediately, as Andy Hunt and Dave Thomas point out in The Pragmatic Programmer, the big advantage with doing DBC of any kind is that it makes you think about the valid state of your inputs, outputs and classes.  This probably goes as far in improving your code quality as the contract checking itself.

But whether you like the idea or not, as of around March 2010, Code Contracts will officially be a part of .Net, so if I were you I’d start looking into it!

About these ads
  1. paul
    November 17, 2009 at 10:51 am | #1

    Maybe I’m getting cynical and jaded… probably just too old, but when I was at university we had a geeky one eyed lecturer (called Steve Maskel-Dobb if you’re interested) that hammered the term “Defensive coding practices” at every lecture he gave (admitted objects were a dot in the gleam of the developers eye, and IDE’s that were more advanced than Edlin were on wish lists of every student)…

    If I wanted a parameter that was defined as a devisor, and knew that could never be 0, I would write an assert. The code would build, and like all good little programmers I would set breakpoints at every expression and condition and ensure that this was hit and catered for correctly. If the assert got hit then there was a point it ended and screamed at the coder that something wasn’t working correctly. If I had a return value, I could write asserts that checked this return value. If I had interface items, I had a test script that ran through interfaces and populated with values that were extreme/wrong to ensure correctness or provide interface level validation.

    I’m just not seeing what a contract provides me with outside of some more code sugar that seems to do what a semi-decent coder would do automatically anyway?

    If there’s a chance of an exception occurring then you should code defensively to make that exception as non-damaging as possible?

    C has had “assert” since its inception, Borland Pascal 3.0 introduced “Assert Begin” (Before that I’m unsure, even I’m not that old!), ok, the Basic boys struggled, but if you went to the mainframe and used PrimosB, you had something similar called “VDat”.

    Am I missing something, or is Microsoft just providing another lazy-mans approach, this time to defensive coding?

  2. Grant
    November 17, 2009 at 12:54 pm | #2

    Sure, it’s not giving you a lot of extra functionality – I mean, .Net has gone 3 ½ versions without it so it can’t be that important!

    The main thing it gives you over asserting is contracts on interfaces, and inherited contracts.

    So for interfaces, you set up the contract on the interface and then every time that interface is used, whatever class it’s implemented by, that contract will be enforced. While you could write a test script that checked interfaces, you’d have to use it on every class that implemented the interface, including any new ones that were added.

    With the inheritance, the contract you specify at the top level gets implemented on all sub-classes. If you were doing the assertions yourself, you’d have to add the assertions in every sub-class method (or always call the base method), and you’d also have to be very careful about Liskov substitution violations (which are catered for by Code Contracts).

    The other main thing you get is the static code checker, which runs at compile-time and tells you in advance whether you’ve written something which is going to violate a contract, although it seems like that’s only really useful in certain circumstances.

    I don’t think it’s a lazy-mans approach though – you have to think about what you’re checking for as much as you would with assertions, it doesn’t really provide any shortcuts (aside from the code snippets), just gives you a more complete checking of the values. If you’re already doing full assertion checks on everything I think it’s beneficial for the points above, and if not then hopefully it would get you thinking about it, which can only be a good thing!

  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


Get every new post delivered to your Inbox.

Join 116 other followers

%d bloggers like this: