Quick Tip: Labeling Loops

Did you know you can label loops in ActionScript 3? Yes, you can! I got inspired by latest tweets referencing source code in image. Lets do some small experiments… Label all of them:

var a:uint, b:uint = 0;
loopA:for(a = 0; a < 10; a++)
    loopB:while(b++ < 100)
        loopC:for each(var c:uint in [0,1,2,3])
            break loopB;

trace(a, b, c); // traces "10 10 0"

Read the rest of this entry »

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 »