November 25, 2014
Hot Topics:

Understanding and Benefiting from Code Contracts in .NET 4.0

  • September 4, 2009
  • By Jani Järvinen
  • Send Email »
  • More Articles »

Introduction

Code Contracts is a new feature in the forth-coming .NET 4.0 release. Currently, Code Contracts is being nurtured as an MSDN DevLabs project, which means it has a life on its own outside the official track of the .NET Framework. Being off the beaten path also means that rapid updates are to be expected, just as has happened with the recent web application frameworks like ASP.NET MVC. Code Contracts is planned to become an official part of the framework version 4.0 once it ships.

The main idea of Code Contracts is to let developers have an easier way to define a set of rules for your classes. For example, you might have rules to which the properties and fields of a given class should always conform to. These rules can then be checked both statically at compile-time and at runtime when the application executes. Code Contracts combines a .NET class library with a Visual Studio IDE integration package, and is available from all .NET compatible programming languages such as C# or Visual Basic



Click here for larger image

Figure 1. Setting up Code Contracts on your development PC is easy.

The age-old problem of maintaining proper internal state of objects has many incarnations: you could raise exceptions, use assertions, or simply fail methods with an error code if the call in the current context would not be valid. Similar things happen when you set property values: a class could want to make sure a percentage value sits between 0 and 100, or a sales price above the cost, for instance.

Although other possibilities certainly exist, the basic implementation of state management is usually this: first, a method checks the validity of parameters and object's current state, and then proceeds to do the real work. After this, the method checks to see if all worked correctly, and as the final step, updates the state of itself accordingly. These checks are often called pre and post conditions, respectively.

When you take a look at the implementation of complex and critical classes, the overhead of validating parameters and maintaining state compared to the real work done by the method can be large. It is not uncommon to see that parameters validation and state management take twice as many code lines as the real work done by a method.

This article will talk about Code Contracts and provide a glimpse of how they can be used in real-world applications. The basics of Code Contracts have already been introduced elsewhere on the Internet.com web sites see (Marius Bancila's article on CodeGuru.com from June, 2009), and this article will only offer a quick recap on the basics, and instead focus in more detail to the workings of Code Contracts.

If you want to try Code Contracts yourself, the easiest way to get started is to download Visual Studio 2010 Beta 1. However, you can also use Code Contracts with Visual Studio 2008 if you first download a separate installer from MSDN DevLabs. You can find links to the download pages at the end of this article. When you install the downloaded package, the installation files will be placed in C:\Program Files\Microsoft\Contracts.

A quick recap: conditions and invariants

To get you up to speed with Code Contracts quickly, the following example shows how Code Contracts can be used from a C# application. Remember that Code Contracts is a technology under construction, and thus changes to the syntax might become necessary as the product evolves. Nonetheless, this is how you could define a Code Contract today:

  using System.Diagnostics.Contracts;
  ...
  public class ContractTest
  {
    private int percentage;
    
    public int Percentage
    {
      get ...
      set
      {
        Contract.Requires((value >= 0) && (value <= 100));
        percentage = value;
      }
    }
  }

In the above code listing, the static Requires method of the Contract class (part of the System.Diagnostics.Contracts namespace) is used to define a pre-condition that specifies that when the Percentage property is set, the value must be between 0 and 100 inclusive. In this form, Code Contracts do not differ much from regular assert statements or throwing for instance ArgumentOutOfRangeException objects. It is said that this enforcement creates a contract for the class, and if the condition is not met, the contract has been violated.

What makes Code Contracts special is that you can enable static, compile-time checks (Figure 2) to learn about contract violations already at compile-time. These checks are by default made asynchronously when you compile your application, and error messages are conveniently shown in the Visual Studio Error List window (Figure 3). Both the static checks and runtime behavior can be configured in the properties window for the project. For instance, you can enable or disable runtime checks for Code Contracts.



Click here for larger image

Figure 2. The Code Contracts page in project options contains many possibilities to configure the technology.



Click here for larger image

Figure 3. Contract violations or verification problems are displayed in the Error List window.





Page 1 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel