Tuesday, April 19, 2011

Design By Contracts


Putting validations all over the places in your code is just like convoluting your code. You must have wondered sometime how good it would be if I could decorate my class with another class at runtime with all the validations.  There are certainly options available with latest .NET framework for e.g. you can use injection to add behavior to your classes at runtime. You may use Unity or any other container to do so. If you are design freak, you must have understood that by all means any implementation to provide change in runtime behavior can be done by using "Decorator pattern" only. I will discuss about this in some other article but what I am going to share with you in this article is how to use Code Contracts. 

Code contract is something which is already present in the framework 4 under the namespace System.Diagnostic.Contracts and heavily used by .NET internal code for e.g. if you expand ICollection, IComparable etc interfaces you will find them using contracts. 
Unfortunately code contracts feature comes by default with Visual Studio Premium and Ultimate edition but if you are using lower version like Professional one, you can still download the external library and make a use of them.
Ok so enough background now let’s jump into the implementation part.

As I said earlier, if you are not using VS 2010 Premium or Ultimate edition, you can download the Code Contract extension from Code Contract Extension

Fair enough, now I am taking a use case where I am providing user a Math divide functionality and I want to make sure that user does not divide the number by zero.

One way I can do it this

 public class MathFunctions
    {
        public double Divide(double number, double divider)
        {
            Debug.Assert((divider == 0), "cannot divide by zero");
            return number / divider;
        }
    }

This will make sure that as soon as my client passes zero, he gets an exception. I can implement divide function as

 if(divider!=0)
    return number / divider;
 throw new ArgumentException();

But this is essentially not part of my business logic and henceforth should not be part of my function. Now I need a way to inject the validation at runtime. Let's see how we can do the same using contracts.

Refer System.Diagnostics;System.Diagnostics.Contracts; namespaces in your code.

I now define an interface which will contain the required method signatures. I will decorate this interface with contract so that my compiler could inject the contract into all concrete implementers of my interface.

  [System.Diagnostics.Contracts.ContractClass(typeof(ITestContractCodeContract))]
    public interface ITestContract
    {
         double Divide(double number, double divider);
    }

You see I am telling compiler that my interface carries a contract which is explicitly implemented in class ITestContractCodecontract. Now time to write the contract class.

[System.Diagnostics.Contracts.ContractClassFor(typeof(ITestContract))]
    public class ITestContractCodeContract : ITestContract
    {
        public double Divide(double number, double divider)
        {
            Contract.Requires<ArgumentException>((divider > 0.0), "You cannot divide by zero");
            Contract.Ensures((number != 1), "abc");
            return default(double);
        }
    }

Again I am decorating this class to tell compiler that this class carries contract for my interface. There are many methods which you would like to look in Contract class (see my references below) but since mostly you would like to write some precondition and postcondition, I am using Requires and Ensures methods of Contract class in my example. Requires provide you a precondition and Ensures provide you a postcondition contract.

Now what my contract class means to runtime, it says that any class implementing my interface divide function if and when called, should first validate (before going into divide function implementation) that divider is not zero and if contract is not broken it should run through the concrete implementation of divide and as soon as it comes out of that function it should make sure my postcondition contract (number not equal to 1) is not breaking.

let me write one concrete implementation of my interface

public class ActualTestContract : ITestContract
    {
        
        public double Divide(double number, double divider)
        {
            //Debug.Assert((divider == 0), "cannot divide by zero");
            if(divider!=0)
                return number / divider;
            throw new ArgumentException();
        }

    }

Now let me call my concrete class and check what happens

internal class Program
    {
        private static void Main()
        {
            ITestContract test = new ActualTestContract();
            double division = test.Divide(1, 0);
            Console.WriteLine("division value is " + division);

            Console.Read();
        }
    }

You see my call actually breaks both pre and post condition but so far if you are copying the above mentioned code in a project and trying to run, you won't get any exception. Actually there is a config setting in your Project -> Properties ->Code contract tab (you will get it only if you have installed the extension) -> check runtime contract checking

If you do so, you will get assertions for both pre and post condition. Please note that if you are using VS2010 premium or ultimate edition, you will get these assertions failing on compile time, since it uses static code analyzer which is able to look into your code contract implementation and evaluate it on compile time it would be able to catch exceptions like NullReference, ArgumetOutOfRange etc.

There might be a case when you want some validations to be applied to your class level. You can do so by writing a method in your class and putting an attribute "ContractInVariantMethod" for e.g.

 [ContractInvariantMethod]
        private void ObjectInvariant()
        {
            Contract.Invariant((this.definition != string.Empty), "You have to have definition properly defined in the class");
        }

The code will be evaluated as soon as instance of this class is visible to any client. It says that no matter what, my instance cannot have empty definition (assume definition is a property inside my class). 

If you want to understand more of Contracts Refer following links

I am attaching herewith my implementation code for you to debug and get a real feel of Code contracts.

Hope this article has helped you understanding the power of decoration and how you can keep your code clean by separating out the aspects (validation, logging, exceptions etc).

Thanks for reading..



kick it on DotNetKicks.com


No comments:

Post a Comment