Sunday, April 26, 2009

If Else is evil

Can you predict the future when you write a new code, or maintaining an old one?

I strongly believe that the answer is yes.

Where to start? Let’s examine one very trivial code segment that is written millions times per day all around the world. The example is written in c# but could be done in any other language. Our current code (extracted from an imaginary existing enterprise application) looks like:

// code 1

static void Main()

{

//let's have currently two choices

//1 - open //0 - close                  

int autotencation = 1;//imagine it is coming as a value at run time.

if (autotencation == 1)

{

              System.Console.WriteLine("Open");

}                                        

else

{

System.Console.WriteLine("Close");

}                   

}     

One year later the product line intruduced a new autotecation value 2 that is to be added to the system.The outcome for using 2 is Wait. Some developer went and added it in the core dll somewhere in the enterprise system. Our code has no idea of it.Let’s see what happen:

//code 2

//let's have currently three choices

//1 - open //0 – close//2 - wait               

int autotencation = 2;//imagine it is coming as a value at run time.

if (autotencation == 1)

{

       System.Console.WriteLine("Open");

}

else

{

       System.Console.WriteLine("Close");

}                   

       What just happened is that if some user executes autotecation code  from above, they will get Close part executed.

This automatically triggers all kinds of events that may be very destructive to the existing system(close acount for example).

A new software Engineer is assign to fix it and he does this:

//code 3

//let's have currently three choices

//1 - open    //0 - close   //2 - wait

int autotencation = 3;//imagine it is coming as value at run time.

if (autotencation == 1)

{

       System.Console.WriteLine("Open");

}

else if(autotencation == 0)

{

       System.Console.WriteLine("Close");

}

else if(autotencation == 2)

{

       System.Console.WriteLine("Wait");

}

Instead Close part to be executed (example code2) we executed nothing. Nothing sometimes is great.

Friday, January 16, 2009

removing xml root

System.Xml.XmlDocument xmlDocument = new XmlDocument( );
string dataSectionMainLoan = string.Empty;
dataSectionMainLoan = @"";
xmlDocument.LoadXml( dataSectionMainLoan );
System.Xml.XmlElement root = xmlDocument.DocumentElement;
....load the xmlDocument here
//remove the artificial root
xmlDocument.ReplaceChild( xmlDocument.SelectSingleNode( "R/NextNode" ), xmlDocument.DocumentElement );