Skip to main content

Code Contracts - .NET Features

How do you make sure your method guarantees to operate correctly under defined expected input states? Well Code Contracts may help you.


One of the fine features provided by .net 4.0 is Code Contracts. First it’s worth thinking a little about what contract means to you. They indicate the expected input states under which the method guarantees to operate correctly.

Contracts act as checked documentation of your external and internal APIs to be shipped. The code contracts are used to improve testing via runtime-checking, enable static contract verification. One of the interesting features of Code Contracts is that it includes a MSIL rewriter (ccrewrite.exe) that post-processes an assembly to change the intermediate language instructions emitted by the compiler. Another great feature of Code Contracts is that you can turn static analysis on and off on a per project basis. I believe this will be important to anyone practicing TDD and BDD.

A code contract follows design principle of Design By Contract (Dbc). This principle has 3 tenets which code contract also takes care of
a) Pre-condition:
Refer to the things it expect to do. These are expressed using Contract.Requires()

b) Post-condition:
Refer to the things it guarantees to do. These are expressed using Contract.Ensures()

c) Object Invariant:
Refer to things it maintains.

These are expressed using Contract.Invariant() Well, the tenets are fine for Dbc and .Net Code Contract follows each of these properly.
We will examine each of them in this article.

How?
The following example illustrates how the three main features of contracts are used.

a) Pre-condition
public Rational(int numerator, int denominator)
{
Contract.Requires(denominator!= 0); this.numerator = numerator; this.denominator = denominator;
}

The preconditions are generally used to specify valid parameter values. The example provided makes sure or checks that the denominator is not equal to zero. We can throw error if the condition is not satisfied using the overloaded method as below.
The example provided makes sure or checks that the denominator is not equal to zero. We can throw error if the condition is not satisfied using the overloaded method as below

b) Post-condition
Contract.Ensures(this.Result!= 0);

Basically the postconditions are checked /Executed before exiting the method call. The example provided checks/ Ensures that the result is not equal to zero. We can throw an exception if the condition is not satisfied using an overloaded method.

Contract.EnsuresOnThrow (this.Result!=0);

c) Object Invariant
public int EMIPercentage
{
get; private set;
}

[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(this. EMIPercentage >= 0);
}

The object invariants are conditions that should hold on each instance of your class whenever the object is visible. They express the condition under which the object is in a “good” state. The methods are identified with [ContractInvariantMethod] attribute. The invariants are checked at the end of each public method call. In the example above the denominator will checked at the end of each public method

Comments

Popular posts from this blog

C# Generic Factory

Implement Factory pattern using generics     public interface IDoWork   {       string DoWork();   }     Declare an Interface first by abstracting the common  functionality    Here I am taking the example of DoWork     public class Manager : IDoWork   {     public string DoWork()     {         return "Manager Manages School" ;     }   }     Implement the IDoWork in concrete classes as shown      public class Teacher : IDoWork     {         public string DoWork()         {             return "Teacher teaches student in school" ;         }     }     public class Student : IDoWork     {         public string DoWork()         {             return "Study in school" ;         }     } This class will actually create an instance of the concrete class so that you can work on that        object further     public class FactoryDemo     {         public T Create

How to enable windows authentication in PostgreSQL

1.     Steps to create user or role in PostgreSQL ·         Open pgAdmin III ·         Login to PostgreSQL database ·         Select “Login Roles” and right click on mouse to view the context menu ·         Select “New Login Role” from context menu ·         Enter desired user name in “Role name” text box ·         Select “Definition” tab in “New Login Role” window ·         Enter desired Password in the given text box ·         Select “Role privileges” tab in “New Login Role” window ·         Select the privileges for the entered user or role ·         Select “SQL” tab in “New Login Role” window ·         This will display the auto generated script ·         Review the script and click on “OK” button ·         Now in the “Login Roles” the newly created role or user “newUser” is displayed ·         Now in pgAdmin III object browser select the database to which the newly created user should be ma

UML - Association, Aggregation, Composition, Generalization, Specialization, Realization and Dependency

Association Association is a simple relationship between two classes. For example A relationship between Professor Class and Student class is known as Association. Both Classes can exist without each other, so Professor and Student are two independent classes. In this kind of relationships there will not be any owner class. Both classes have their own life cycle. UML Notation:     Aggregation Aggregation is a special type of Association. It is known as “Has-A” relationship. For example A Department class can contain Professor Class. Here Department class is owner class. Here in this relationship even after deleting Department class, Professor Class can exits. UML Notation: Composition Composition is a special type of Aggregation. It is known as “Is-A” relationship. For example A University Class has many Department class. Here University and Department objects are dependent on each other. If we delete University cl