Thursday, September 18, 2014

Tackling the Arrow head Anti-Pattern

Frequently you will see following type of code in your code base.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if(result != 1)
{
    if(someOtherResult == 101)
    {
        if(anotherValue == 500)
        {
            // do something
        }
    }
    else
    {
        // do some other thing
    }
}
return;
Here the code forms a shape of an arrow-head, as below:
?
1
2
3
4
5
6
7
8
9
if
    if
        if
            if
                do something
            end
        end
    end
end
If you see, the main logic is deep down into the nested condition, it increases the cyclomatic complexity of the code.
A better version of the same code could be as below:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
if(result == 1)
{
    return;
}
if(someOtherResult == 101 && anotherValue == 500)
{
    // do something
    return;
}
// do some other thing
return;
The above code does a number of things to flatten the code and make it better:
  1. Validations are performed first and it returns at the first opportunity.
  2. Multiple nested conditions are combine into one (with “&&”(logical And) operator. If there are multiple expressions forming one such condition, they can be moved to a separate method returning boolean. That method can then be use in the if condition as below:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
if(IsValidResult(someOtherResult, anotherResult)
{
    // do something
    return;
}
bool IsValidResult(int someOtherResult, int anotherResult)
{
    if(someOtherResult == 101 && anotherValue == 500)
    {
        return true;
    }
    return false;
}

No comments:

Post a Comment