Wednesday, April 20, 2011

Beware of Constants


Let say I have a third party library having code as following

namespace Test
{
    public class TestClass
    {
        public const string NAME = "Abhishek Tiwari";
    }
}

My application uses this library and prints this name on console in following manner

internal class Program   
{        
      private static void Main(string[] args)        
       {             
          Console.WriteLine(Test.TestClass.NAME);             
          Console.ReadLine();         
       }    
}

After sometime my library provider company is owned by some other company and changes the const value to something public const string NAME = "I am no more Abhishek Tiwari";

Now as being a loyal customer to that company, you get  the new version of the library and replace the old version by it and now click on your executable again.

Whack!!! You still see "Abhishek Tiwari" written on the console. 

So what happened in the background is mystery for you but before you bang your head here and there in confusion, let me solve this puzzle for you. 

Actually when you last built your project, your compiler has put the hard-coded values in place of consts everywhere in your IL so those consts values no more refer to any part of the code whatsoever. If you look into the IL, you will find something like

//My IL (compiled code)
internal class Program   
{        
      private static void Main(string[] args)        
       {             
          Console.WriteLine("Abhishek Tiwari");             
          Console.ReadLine();         
       }    
}

So even if now I have updated the third party without rebuilding my code (since it is essentially not required) my IL will remain same, and in my IL const "NAME" which was linked to third party is vanished, leaving hard coded const value behind.


Get working code from TestConst

I hope if you are a third party provider, you will keep this in mind to avoid any shock. I am not sure what is the best possible solution for this (will keep you posted, if I come across any) but for now you can change your "const" type by "static readonly" so that your library consumer can always see the modifications.



** Thanks to Shailendra (Author in aspnettechstuffs) for sharing this valuable information with me.



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


Thursday, April 14, 2011

Anonymous method exposed

In this post, I am going to explain what Anonymous function is and how CLR interprets them.
Anonymous functions were introduced in .NET 2.0. They provide you the in place code block where a delegate object is acceptable.  Anonymous method can reduce the overhead of declaring a function and you can declare them right at the point of the invocation.

    public class AnonymousFunction
    {
        public delegate void delFunc();
        public void Test()
        {
            int i = 4;
            delFunc delFunc = delegate
            {
                i += 1;
                int j = 0;
                if (i > 1)
                {
                    Action<int> del = delegate { j += 1; i += 1; };
                    del(8);
                }
                Console.WriteLine("i: " + i.ToString() + " j: " + j.ToString());
            };
            delFunc();
        }
    }

You can see in the code above that we have used anonymous methods to give implementation to our delegates delFunc and del. The key point to note here is the variable scope within the anonymous method block. An anonymous method has all the variables available to it that your code can access at the point where anonymous method is declared.  This makes it anonymous method even more useful but on the other hand writing anonymous methods all the places can make your code unmanageable as well.

Now the question comes, how compiler interprets them. For compiler any method should have an associated type so it has to be either instance method or static one. Compiler checks what all resources your anonymous method is using and based on take the decision how it needs to be implemented in your MSIL.

Compiler essentially creates a private class for each anonymous method and makes all variables used inside your anonymous method as the member variable of that private class and sets those member variables from outside (invocation point) with the value of same variables declared in the main class.

To get more understanding of it, let’s see what intermediate code compiler will emit for the above mentioned code. I am simplifying the actual compiler code here for your better understanding

private sealed class MyClassForDelFuncAnonymousMethod
{
    // Fields
    public int i;
 
    // Methods
    public void MYDelFuncAnonymousMethod()
    {
        this.i++;
        int j = 0;
        if (this.i > 1)
        {
            MyClassForDelAnonymousMethod oMyClassForDelAnonymousMethod = new MyClassForDelAnonymousMethod();  
oMyClassForDelAnonymousMethod.j = j;
oMyClassForDelAnonymousMethod.oMyClassForDelFuncAnonymousMethod = this;
 
        Action<int> del=  oMyClassForDelAnonymousMethod.MYDelAnonymousMethod(8);
 
        }
        Console.WriteLine("i: " + this.i.ToString() + " j: " + j.ToString());
    }
 
    // Nested Types
    private sealed class MyClassForDelAnonymousMethod
    {
        // Fields
        public AnonymousFunction.MyClassForDelFuncAnonymousMethod oMyClassForDelFuncAnonymousMethod;
        public int j;
 
        // Methods
        public void MYDelAnonymousMethod (int)
        {
            this.j++;
     this.oMyClassForDelFuncAnonymousMethod.i++;
        }
    }
}
 
 
public void Test()
{
    int i = 4;
        MyClassForDelFuncAnonymousMethod oMyClassForDelFuncAnonymousMethod = new MyClassForDelFuncAnonymousMethod();
oMyClassForDelFuncAnonymousMethod.i = i;
        i++;
        k++;
 
        AnonymousFunction.delFunc delFunc = new AnonymousFunction.delFunc(oMyClassForDelFuncAnonymousMethod.MYDelFuncAnonymousMethod)
 
}


Wednesday, April 13, 2011

Typeof vs GetType (how to compare types)



Let say I have implemented few classes in following manner


Public Interface IA
    Property Id As String
End Interface

Public Class A
    Private _id As Integer
    Public Overridable Property Id As Integer
        Get
            Return _id
        End Get
        Set(ByVal value As Integer)
            _id = value
        End Set
    End Property
End Class


Public Class B
    Inherits A
    Implements IA


    Public Property Id As String Implements IA.Id

        Get

        End Get
        Set(ByVal value As String)

        End Set
    End Property
End Class
               
Now I write switch statement to compare type like these ways

Dim a As IA = New B
        a.Id = "2"
        Dim b As A = New B
        b.Id = "2"

        Dim t As String = a.GetType.ToString
        Select Case t
            Case GetType(A).ToString
                Console.WriteLine("type is a")
            Case GetType(B).ToString
                Console.WriteLine("type is b")
        End Select

        Select Case True
            Case TypeOf a Is A
                Console.WriteLine("type is a")
            Case TypeOf a Is B
                Console.WriteLine("type is b")
        End Select

        Select Case True
            Case TypeOf b Is A
                Console.WriteLine("type is a")
            Case TypeOf b Is B
                Console.WriteLine("type is b")
        End Select


Now note that the yellow one will print “type is b” but green one will print “type is a”. actually "is" operator traverses the complete hierarchy to match the type so typeof a is “IA”,”A”,”B” all true. But GetType does not return you the type of reference instead actual type since it is calculated on runtime so it will just give you a.GetType = B only.

Now let me share with you some interesting methods from System.Type namespace which works ofcourse on runtime and can be very handy.

Let me first define some dummy interfaces, classes and their relations.

 interface IBase
    {

    }
    
interface IA : IBase
    {

    }

    
class A : IA
    {

    }

    
class B : A
    {

    }

Now let me create few objects out of that

IBase ibase = new B();
IA ia = new B();
A a = new A();
B b = new B();

Now I want to see if type of my object b is derived from type of my object a. There are two methods
1. Type.IsAssignableFrom
2. Type.IsSubclassOf

  // x.IsAssignableFrom(y) returns true if:
  //   (1) x and y are the same type
  //   (2) x and y are in the same inheritance hierarchy
  //   (3) y is implemented by x
  //   (4) y is a generic type parameter and one of its constraints is x

IsSubclassOf function does just reverse of IsAssignableFrom. So if (typeof)x.IsAssignableFrom(typeof(y)) is true then (typeof)y.IsSubclassOf(typeof)x) will also be true.
Kindly note that the above two functions are valid on concrete types only. I will explain how to get types for interface in a minute, hang on.

let's get some working examples (refer above mentioned classes and objects)

1. ia.GetType().IsAssignableFrom(a.GetType()) will return false since actual type of ia is "B".

2. a.GetType().IsAssignableFrom(ia.GetType()) will return true since object of type of ia ("B") can be assigned to type of a ("A")

3. b.GetType().IsAssignableFrom(a.GetType()) will return false since b is not assignable from a type

Now some examples of IsSubclassOf

1. a.GetType().IsSubclassOf(ia.GetType()) will return false since ia (type "B") is not base class of a (type "A").
2. b.GetType().IsSubclassOf(a.GetType()) will return true since "B" is subclass of "A".

Let's discuss about checking the interface type now

If I want to see how many interfaces are implemented by the type of my object we can use GetInterfaces method

Type[] types = ia.GetType().GetInterfaces();
will give me types[0] = "IBase" and types[1] = "IA"

If I want to see whether a particular type is implemented by my object type, I can use GetInterface method and pass interface name as string parameter.

Type type = ia.GetType().GetInterface("IA");
will return me IA (interface type) since type of ia ("B") implements it.

similarly
Type type = b.GetType().GetInterface("IBase");
will also return me IBase type since my object b has that in its hierarchy.

Now what if I do something like
Type type = ia.GetType().GetInterface("I");
where I is some unrelated interface. you might have guessed it correctly type object will be null and we can tell that my object type never has interface "I" type in its complete hierarchy.