Wednesday, September 10, 2008

Good code layout.

Recently I have been looking at and writing a lot of c# code. It's nice when you get paid to program in the language you want to learn. I have noticed in several places where people build the same complete object with one or two difference in two separate locations in the code usually a if else statement. I have a big belief in don't repeat yourself when programming. If you find you are writing the exact same code or close to it over and over again you are doing something wrong. Here is a good example of what I am talking about. It also isn't too far from the code that made me want to write this post.



String Foo1 = "3.4.5";
String Foo2= "3.4.6";
mObject boo = null;
if(new Version(Foo1) > new Version(Foo2))
{
    boo = new mObject
    {
        vLam = "yummy",
        jArp= "jello",
        cFile= "No"
    };
}
Else
{
    boo = new mObject
    {
        vLam = "yummy",
        jArp= "jam",
        cFile= "Yes"
    };
}

In the above code we see an example of what not to do. You are creating dynamic objects to make a decision that could be made using a string comparison operator which isn't really on topic but is worth mentioning. Also you have double the code you need in creating your object.


Now let's do it in the cleaner way that I would like to see one instantiation and then just assign the values as we go.



String Foo1 = "3.4.5";
String Foo2= "3.4.6";
bool isFoo2Less = Foo1.CompareTo(Foo2) > 0
mObject boo = new mObject
{
    vLam = "yummy",
    jArp= (isFoo2Less)? "jello" : "jam",
    cFile=(isFoo2Less)? "No" : "Yes"
};

We end up with less lines of code and even though we add a variable to the mix and do two checks. The maintainability of this code is much easier and will cause less confusion over the life of the program.

4 comments:

Ishpeck said...

You're so picky. It works either way.

Erin said...

You are correct it works either way but the my way will be easier to maintain latter on in life. It is similar to putting code in a function rather then just cutting and pasting it over and over again.

Ishpeck said...

It isn't necessarily easier to maintain. It's just quicker to read.

James and Crystal said...

You're wrong. Running the ? operator executes faster in most all languages and using less if statements overall means code is less likely to be error prone. You're correct in that they evaluate the same but Derkin's solution is far superior to the long winded if/else mantra that lower level devs use. This IMHO is the difference between trancendant code gods and the lowerlings that take orders from said gods.