Code optimization

First, my golden rule: method with more than 12 rows is too long. Methods should be short, simple, clean and reusable. In most cases your methods fits into 5-12 rows. If not, you should consider rewriting your methods.

Look at the next code. There is too much nested tests. Soon you get lost with more and more nested levels:

function gimmeResult(a, b, c)
{
    var result;
    if(a)
    {
        if(b || c)
        {
            if(b && c < 0)
            {
                result = 1;
            }
            else
            {
                result = 2;
                // where am I?
            }
        }
        else
        {
            result = 3;
        }
    }
    else
    {
        result = 4;
    }
    return result;
}

Try to linearize code, it is much more cleaner for reading when no multiple nesting used:

function gimmeResult(a, b, c)
{
    if(!a)
        return 4;
    if(!b && !c)
        return 3;
    if(b && c < 0)
        return 1;
    return 2;
}

Read the rest of this entry »