Sep 5, 2013

Code Contracts

Code Contracts

Code Contracts are static library methods used from any .NET program to specify the code’s behavior. Runtime checking and static checking tools are both provided for taking advantage of contracts. Code Contracts is a subset of a larger Microsoft Research Project called Spec# (pronounced "Spec Sharp"). 

In simple, its add-on that you can install in Visual Studio. This library offers number of attributes and helper classes to perform various validations/conditions at various levels.

You can download add-on from here

After installing make sure you have "Code Contracts" tab in project properties.


Make changes to project properties as below:



Add Using statement as below:
using System.Diagnostics.Contracts;


Preconditions:
Preconditions are those which needs to be executed at the beginning of the method. They generally used to validate parameter values like object is not null, Argument null exception, int > 0 etc.

Normal precondition looks like this:

public static int GetEmployeeCount(int intDeptId)   {
         if (intDeptId == 0)
           throw new Exception("Invalid Department Id");
            
        //logic here
        return 10;
}

We can write the same code in a better way as below:


public static int GetEmployeeCount(int intDeptId)   {        Contract.Requires(intDeptId > 0);
       //logic here
       return 10; }




Static Checking:
Instead of raising exception after callign method, it would be much easier if we can raise exception at the time of calling method. This is static checking. For this, you need to enable "Show squigglies" option in Project properties.

Code:
public static int GetEmployeeCount(int intDeptId)
  {
      Contract.Requires(intDeptId != 0,
             "Zero is not allowed for Department Id.");
      //logic here
      return intDeptId;
}

While performing static checking, error message will be shown as below:



Post-Condition:
These conditions are nothing but validations after executing a method. These are very useful in case of validation objects, dataset from database, etc. You have option to save old values in OldValue before calling method.
In below example, we are ensuring the output of the GetEmployeeCount is greated than 5.

Code:

Contract.Ensures(Dept.GetEmployeeCount(5) > 0);


Interface Contracts:
We can write contracts for interface methods required creating contract class to hold them.

We can use below attributes:
ContractClass: Need to defined for Interface. Ex: [ContractClass(typeof(IDeptContract))]

ContractClassFor: Need to defined for class implements interface. Ex: [ContractClassFor(typeof(IDept))]

Conclusion:
Code Contracts will be very useful, if we can use it in a proper manner and follow some guidelines. This can be used in Business Layer for validating objects before passing it to Data Layer. This will reduce lines of code and errors/mistakes while writing validation logic.

For complete documentation, please refer this link



No comments:

Post a Comment