Vanguard Coder

Simple Life of a Keen Developer

Smelly IFs

leave a comment

In my years of experience, the most common repeat offender I’ve seen is the excessive use of IF Statements. As a result. I’ve joined the Anti-IF Campaign.

It results in code that is hard to change, maintains, and does not use composition, inheritance, or design patterns to write meaningful code. It is just a code that runs. I’ve spent hours trying to find out bugs in if statements written in butterfly form (nesting going 3-5 levels deep). Try adding a feature to an If statement at the 3rd level which goes down 5 levels. This won’t give you much confidence that it won’t have unintended side effects.

There are some examples in which it may be hard to get rid of such as Mark Needam pointed out unless some overkill solution is applied (Attributes, Validation blocks), but the other common offenders can be removed.

Scenario #1

if ( expression == true)
{
    return true;
}
else
{
    return false;
}

This could be shortened to:

return expression;
Scenario #2

if ( expression = somestring)
{
    return processA;
}
else
{
    return processB;
}

This could be shortened to (VB, or use ?: in C#)

DirectCast(IIF(expression=something), processA, ProcessB), returntype)

The disadvantages is both – processA and ProcessB will be evaluated, possibly making the process inefficient. In 2008, If method was introduced, and direct casting is not necessary. So this can be changed to:

if (expression == something), processA, ProcessB)

Scenario #3

Avoid If at the start of a method and end if near the end. If should not span the whole method.

Scenario #4

If you have nested if’s, see if there are better alternatives. This makes maintenance and manageability of the code difficult. Excessive if’s points towards procedural code, thus should be limited (but not necessarily entirely avoided).

Scenario #5

public void MethodA() {
    if (condition1) // note first line is an if
    {
        50 lines, nesting goes down to three level
    }
else if (condition2)
    {
       similar issue as above
    }
else if (condition3)
    {
        similar issue as above
    }
}

This is probably bad design, and could be replaced by various patterns to make life easier.



Written by zkashan

May 21st, 2012 at 8:48 pm

Posted in Uncategorized

Leave a Reply