Design by Contract with .NET 4.0

An entry about visual studio | .net 4.0 Publication date 6. November 2008 16:33

Justin van Patten has put together a great list of all the new features that will ship with .NET 4.0 – both new features in the BCL, as well as the new features in the C# language itself. One of the additions to the BCL comes from Microsoft Research, and is called Code Contracts.

Code Contracts is a language independent tool which allows you to embed rules about the inputs, outputs and invariants in your code. When this information is embedded in the code, the Code Contract tools can perform both static and runtime analysis of the code to ensure that it is not breaking any of the rules defined. Sounds a lot like Spec#, doesn't it? Well, Code Contracts is essentially a port of the static and runtime verification concepts from Spec# into an API which will ship as part of the .NET 4.0 Base Class library.

Let´s look at an example: Imagine that we have an API with the following silly method somewhere in it:

public static string GetTypeName(object obj)

{

    if(null == obj) throw new ArgumentNullException("obj");

    return obj.GetType().Name;

}

The problem with this, is that there´s no way for a client of this API to know what happens if they pass a null value to this method. Does it crash? Return a null? Return an empty string? By using the Code Contract API, we can make such details of our implementation explicit:

public static string GetTypeName(object obj)

{

    CodeContract.Requires(null != obj);

    return obj.GetType().Name;

}

If someone writes code that calls this method and passes a value that might be null, and we have static checking of code contracts turned on in our project, we will get the following warnings from the compiler:

image

The first warning tells us that the contract we have defined was violated (not very helpful the messages yet, but it is an early beta after all), and the second warning points us at the code that is violating the contract.

In addition to setting up contracts that constrain the inputs to a method, we can also set up contracts that talk about the outputs. for instance, imagine that our original method looked like this instead:

public static string GetTypeName(object obj)

{

    return null != obj ? obj.GetType().Name : "<null>";

}

This time, our method will happily accept an argument which is null, and it will always return a string. Using code contracts, we can embed this fact into our method:

public static string GetTypeName(object obj)

{

    CodeContract.Ensures(CodeContract.Result<string>() != null);

 

    return null != obj ? obj.GetType().Name : "<null>";

}

These examples are just scratching the surface of what is possible. In addition to defining contracts that talk about the entry and exit points of methods, there´s also invariant contracts that deal with the state of the object as a whole. Contracts can also be defined on interfaces. More tools that take advantage of the contracts will also become available – for instance tools that auto-generate documentation, and of course there are great opportunities for integration with PEX here.

If you want to learn more about the features available and how they all actually work under the covers, then check out the recording of the PDC 2008 session by Mike Barnett and Nikolai Tilmann over at Channel9. I really recommend watching it – they do a great job of explaining the concepts (the first part is about Code Contracts, the second about PEX).

You can also go and download a preview of the framework and tools for Visual Studio 2008 over at the Microsoft Research site.

Currently rated 3.3 by 3 people

  • Currently 3.333333/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Powered by BlogEngine.NET 1.4.5.0

Welcome!

My name is Fredrik Kalseth, and this is my blog - thanks for visiting! I am fortunate enough to work with what I love for a living, and this blog is essentially the biproduct of that.

I work as a senior consultant for Capgemini, and am also an active participant in the Norwegian .NET community, as an avid attendee but also as a speaker (most recently at NNUG and MSDN Live).

As a developer, I have a wide circle of interest. My primary passion is for agile, test-driven development, with focus on best practices and clean code. That said, I also love to work on the frontend, especially with web development.

On Twitter? My handle is fkalseth. On LinkedIn? I`m there too.

NDC 2010

The conference to attend this summer happens June 16th-18th in Oslo, Norway. Are you going? Be sure to catch my talk on AOP while you're there!

 

Disclaimer

This is a personal blog; any opinions expressed here are my own and do not necessarily reflect those of my employer. All content herein is my own original creation, and as such is protected by copyright law. Unless otherwise stated, all source code posted on this blog is freely usable under the Microsoft Permissive License.

What Readers Talk About

Comment RSS