CLR 4.0: Code Contracts

Note: This blog post transferred from my OLD BLOG and was originally posted in 2008.

As part of making the .Net framework fully support Design by Contract approaches, the BCL team along with the CLR team had integrated very powerful project from Microsoft Research (MSR) named Code Contracts, and what code contracts do for you as giving you declarative, integrated, and easy way to express all the facts you already know about your program by design to make it work better.

Before you used to do that using Assert statements or even using some comments on top of your API telling people what’s the rules they should follow in order to perfectly use your Methods, one major thing about those methods that it wasn’t a Must to Follow, on the contrary Code Contracts is enforcing and checked statically at compile time and dynamically at runtime.

Note: At this CTP build of Visual Studio and .Net Framework, the Static Analysis tools is not supported yet, but the dynamic runtime checking is supported

Microsoft decided to provide Code Contracts as Library Solution instead of Language Solution that’s to make them widely used by all the languages using .Net framework, So new in .Net Framework 4.0 BCL under System.Diagnostics.Contracts you will find the code contracts library.

All Code contracts grouped under CodeContract static Class as Static Methods that return void, each Contract Methods has 2 overloads; One takes a Boolean expression that must be true in order for contract to be valid and another overload that take expression and a message to display in case of contract violation, things you should know about contracts:

  • Declarative
  • Come at the beginning of the function
  • Think about them as part of the method signature.
  • Your contracts can have only Boolean Expressions.
  • You can but methods calls inside your contracts but this method must be marked as Pure.
image

How to use Contracts

Defining contracts is fairly easy as adding couple of checking lines at the start of the method, check the following sample calculator class to understand how you can use contracts inside your classes:

 1: public class Calculator
 2: {
 3:     /// <summary>
 4:     /// Adds 2 numbers
 5:     /// </summary>
 6:     /// <param name="x">First number can't be zero</param>
 7:     /// <param name="y">Second number can't be zero</param>
 8:     /// <returns>Sum of the 2 numbers</returns>
 9:     public int Add(int x, int y)
 10:     {
 11:         CodeContract.Requires(x > 0 && y > 0);
 12:
 13:         return x + y;
 14:     }
 15:
 16:     /// <summary>
 17:     /// Subtract 2 positive numbers
 18:     /// </summary>
 19:     /// <param name="x">First Number must be larger than the second</param>
 20:     /// <param name="y">Second number</param>
 21:     /// <returns>Result of subtraction, can't be negative</returns>
 22:     public int Sub(int x, int y)
 23:     {
 24:         CodeContract.Requires(x > y);
 25:         CodeContract.Ensures(CodeContract.Result<int>() > -1);
 26:
 27:         return x - y;
 28:     }
 29: }

Types of Contracts

CodeContracts has 3 main types:

1. Preconditions

Use them to validate your method parameters, they must be true at method entry for successful execution of the method.  It’s the responsibility of the caller to make sure these conditions are met.

    • CodeContract.Requires(x>= 0);
    • CodeContract.RequiresAlways(x>= 0);

The difference between Requires and RequiresAlways is the last one always included even in release builds, so you can use it for contracts that you want to include in your release.

2. Postconditions

They are declared at the beginning of a method, just like preconditions.  The tools take care of checking them at the right times.their jobs is to ensure that methods has successful closure.

    • CodeContract.Ensures(z != null); // must be true if method closes successfully
    • CodeContract.EnsuresOnThrow<IOException>(z != null); // Grantuee some variable status in case of specific exceptions.

Also it is very often necessary to refer to certain values in postconditions, such as the result of the method, or the value of a variable at method entry.  CodeContract class allow this using some special referral methods; they are valid only in a postcondition.

    • CodeContract.Ensures(CodeContract.Result<Int32>() >= 0); //represents the value results from a method
    • CodeContract.Ensures(x > CodeContract.OldValue(x)); // represents the value as it was at the start of the method or property.  It captures the pre-call value in a shallow copy.

3. Object Invariants

They are contracts that must be true at all public methods exists in an object. They are contained in a separate method that is marked with the ContractInvariantMethodAttribute.  The method must be parameter-less and return void.  That method contains some number of calls to the CodeContract.Invariant method.

   [ContractInvariantMethod]
void ObjectInvariant() {
CodeContract.Invariant(someData >= 0);
}

What do you ship?

image The final question that matters is what I’ll deliver the customer, in reality Code contracts has a very intelligent way of generating its own contract assemblies, so you have your old normal .net assemblies without contract that you can release to your customers and don’t worry about the performance hit, and another assembly contains the contracts only without any code; you can deliver those assemblies to your customer that you want them have the same code checking experience you have during compile time.

More Information:

  1. Microsoft Research’s code contracts website.
  2. PDC 2008: PC49, Microsoft .NET Framework – CLR Futures (Video|PPTX).
  3. PBC 2008: TL51 Research: Contract Checking and Automated Test Generation with Pex (Video|PPTX).
  4. Introduction to Code Contracts [Melitta Andersen].

Related Articles:

  1. CLR 4.0: Type Embedding.
  2. CLR 4.0: New Enhancements in the Garbage Collection
  3. CLR 4.0: Corrupted State Exceptions

Hope this Helps,

Ahmed

Advertisements

CLR 4.0: Dynamic Languages Support

Note: This blog post transferred from my OLD BLOG and was originally posted in 2008.

As more and more dynamic languages start to show up in the .net world like IronPython, IronRuby, and F# the need for some changes in the CLR and the BCL to natively support those languages become important. But what’s really beautiful about CLR is it’s well designed framework, and eventually Microsoft discovered that the changes they need to make is not that much, Jim Hugunin built a Full Dynamic Language Runtime (DLR) on top of the CLR and he didn’t ask them for a lot of changes.

Some of the Changes in CLR 4.0 in order to support Functional and Dynamic Languages are:

    1. BigIntegers
    2. Tuples

BigIntegers

Jim Hugunin asked Anders Hejlsberg What is the sum of 2 billion and 2 billion; Anders answered – 2 billion :D, this joke was the primer in a lot of the last PDC sessions! And the fact that C# compiler simulate the nature of 8 bytes numbers in the current microprocessor architecture is not something the C# community to be ashamed of, because this is the what the microprocessor designed to do and you don’t want to have different behaviors. But the the fact that still in normal numeric processing you have the normal behavior of adding 2 large numbers like 2 billion should give you the result of 4 billion, and it make all the sense.

So, if you’ve try to execute this operation (2000000000 + 2000000000) on the current C# compiler you should get the following result, and of course the compiler is smart enough to detect that you are doing an operation that will cause an arithmetic overflow, so you have to use the uncheck key work to stop the compiler check on arithmetic overflow exception (for more details review my post: Silent Overflow in CLR).
image
image New in CLR 4.0 and BCL 4.0, you will find a new type BigInteger under System.Numerics namespace, the CLR team cooperated with the Optima team “Microsoft Solver Foundation” to provide reliable, optimum, and fast BigInteger Type in .Net base class library. supporting this new type as library solution means all languages can benefit of this functionality no matter it’s dynamic or not. so C# will have BigIntegers as IronPython too.

Tuples

The Tuple is a mathematical term and it simply means an ordered list of values, those values are the internal items of this tuple and you can access those items by referencing them directly with their position in the sequence. To be more specific the Tuple is kind of On Fly Struct, you don’t have to define names for its internal items to access, you just access them by index!

Tuple requested to be supported by F# team and IronPython team, and they are supported natively in this languages. The CLR team have worked hardly with all the language teams and come up with final implementation for a Tuple library that everyone is happy with.

So new in .Net 4.0 under the system namespace you will find a generic type called Tupletakes up to 7 generic types although hi didn’t saw tuples takes that much items on fly! with library solution support the other languages like C# will not natively need to support tuples, so there will be no keyword for tuple in C#.here is an example on how to use tuples:

var tuple1 = Tuple.Create(4, ‘ahmed’);
var item1 = tuple1 .Item1;
var item2 = tuple1 .Item2;


image

A typical usage for Tuple is as a return type for a method need to return multiple values instead of using out parameters you can use a tuple because it’s easy to create on fly, for instance in this quick example i’ve built a function adds a new item into a collection the logic of this function is to search first if the item exist already in the collection; and if item founded, function return a Boolean value of false determining failure of adding the item and also the index of the already existed item, you could use out parameter of course for doing the same job which i still prefer!

 1: public static

Tuple

<bool,int> AddItem(string item)
 2: {
 3:

var

 result;
 4:
 5:     //if item exists in the collection, return A tuple with 
 6:    // false, and the index of the existed item in the collection.
 7:     if (collection.Contains(item))
 8:     {
 9:         result =

Tuple

.Create(false, collection.IndexOf(item));
 10:     }
 11:     // if item doesn't exist in the collection, add the item and return 
 12:    // a tuple with true and the index of the inserted item.
 13:     else
 14:     {
 15:         collection.Add(item);
 16:         result =

Tuple

.Create(true, collection.Count - 1);
 17:     }
 18:
 19:     return result;
 20: }

Last advise about Tuples, don’t use them in public APIs and methods, it will makes your code harder to understand although it’s easier to create Tuples but the internal data structure of the Tuple must be documented very well and known by the user of your function in order to use it right, on the contrary of out parameters the user of your method just need to read your parameter name to understand its job!

More Information:

  1. PDC 2008: PC49, Microsoft .NET Framework – CLR Futures (Video|PPTX).
  2. PBC 2008: TL10 Deep Dive, Dynamic Languages in Microsoft .NET(Video|PPTX).
  3. Wikipedia: Tuple

Related Articles:

  1. CLR 4.0: Type Embedding.
  2. CLR 4.0: New Enhancements in the Garbage Collection.
  3. CLR 4.0: Corrupted State Exceptions.
  4. CLR 4.0: Code Contracts.

Hope this Helps,

Ahmed