36

In order to fully understand and take advantage of the new features and enhancements provided with the coming of the new .NET Framework 4.0, I would like to get an example of real-world application of Code Contracts.

  1. Anyone has a good example of application of this feature?

I would like to get a code sample with a brief explanation to help me get up and running with it.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Will Marcouiller
  • 23,773
  • 22
  • 96
  • 162

4 Answers4

24

From The Code Contracts User Manual:

Contracts allow you to express preconditions, postconditions and object invariants in your code for runtime checking, static analysis, and documentation.

Code Contracts are used for static verification; imagine if - at compile time - you caught not only syntax errors but also logic errors. This is the vision of static program verification.

Real World Example

You could use contracts (and static verification) to reduce the cost of testing... in particular regression testing. As an example, let's say I write some code which fulfills some business needs... but later, performance needs change, and I'm required to optimize. If I first write a contract, then - when my new optimized code is verified - if it no longer fulfills the original contract I'll get an error message in my IDE, just like if I had a compile time error. As a result, you find and resolve the bug almost immediately, which costs less than a round of testing.

Richard JP Le Guen
  • 28,364
  • 7
  • 89
  • 119
  • Thanks :) Also, JML4 is a static verifier for Java, which allows you to write pre-conditions and post-conditions (in essence a simple contract) in annotations. For those interested: http://sourceforge.net/apps/trac/jmlspecs/wiki/JML4 – Richard JP Le Guen May 27 '10 at 19:05
14

There is a freely available chapter about code contracts in the upcoming book C# in Depth, second edition. By some guy named Jon Skeet, some of you may be familiar with him :)

As for practical usage. You can use them anywhere in your code, but especially if you're developing framework / API type libraries that lots of people will be using, I expect them to come in quite handy. Static verification of your code saves a lot of time compared to finding out at runtime that you didn't handle some edge case.

You may document your method usage all you like, but will people actually read that documentation? Is it allowed to have string parameter x in method y be null, or not? Code contracts can provide that information, to take the guesswork out of the equation.

Here's an example of just such a case:

static int CountWhitespace(string text)
{
    Contract.Requires<ArgumentNullException>(text != null, "text");
    return text.Count(char.IsWhiteSpace);
}

The verification will complain if anyone tried to pass a string to CountWhitespace that might be null. In addition, it will throw an ArgumentNullException at runtime.

I've only recently converted my private class library to .NET 4.0, but I plan to add code contracts to it real soon.

Thorarin
  • 47,289
  • 11
  • 75
  • 111
  • Do you have a real-world example, as the OP requested? – Robert Harvey May 27 '10 at 17:56
  • 4
    The PDF article I linked is full of examples? I suppose I could paste them in, but it would be better to read the whole thing. – Thorarin May 27 '10 at 18:00
  • +1 For showing `Contract.Requires()`. Very useful method for replacing if (x) throw y blocks. – aaaantoine Apr 25 '14 at 15:45
  • Sweet, does this(throwing error) work even if the developer does not have the contract tools installed? – Tony Sep 16 '14 at 16:58
  • The PDF mentioned is no longer available at the provided link. It simply redirects to the book's web page itself, which no longer offers that chapter as a free download. – Knowledge Cube May 02 '17 at 15:05
8

There is a lot of places where contracts are used in .Net. >>Sources<<

Roman Bats
  • 1,775
  • 3
  • 30
  • 40
  • 2
    Providing .NET Framework source code along with the usage done of Code Contracts definitely answers the requirement of a real world example. =) (+1) – Will Marcouiller Nov 26 '14 at 19:34
5

Have you ever seen a NullReferenceException and wished that the compiler could have warned you about it at compile time to avoid finding out the hard way - with your program crashing?

With code contracts you can write things like:

Contract.Requires(foo != null);

This isn't just a runtime check - you can set it up so that if you call this function with an argument that might be null you will get a compile error.

Here's a real world example:

Address GetAddress(Customer customer)
{
    Contract.Requires<ArgumentNullException>(customer != null, "customer");
    return addressBook.FindCustomer(customer);
}
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452