if() return;

I decided to write a quick little post about the advantages of using “return”. Return works in a really cool way (for those of you who don’t know).

Traditionally you use it like this:

// whatever comes after the colon determines which type to return (String, Number, CustomObject, ect.)
function returnAValue(foo):String
{
// in this case foo will be a String
return foo;
}

//outputs testing
trace(returnAValue(“testing”));

If you’ve never used return - it’s a really nice way to do calculations.

function add(num1:int, num2:int):int
{
var finalNum:int = num1+num2;
return finalNum;
}

var newNumber = add(5, 8);
trace(newNumber); //outputs 13
 

Basically - it runs the function - and then gives back the caller of that function a value. It’s built so that at the return - the function stops running and returns the value you tell it to. Another standard way of using return is to use it as a way to stop a function from running. This is a really streamlined way of using a conditional.

I never really used return in my early days.

Let’s say you have a button that when you rollOut - you only want it to animate if it’s not selected.

Here’s how I used to do it:

function onRollOut(m:MouseEvent)
{
if(!selected)
{
doAction();
}
}

That’s fine - but if you have other conditionals in there your eyes can get lost quickly in all the mumbo jumbo. Something I’ve really been striving for lately is really readable code.

A more efficient way or writing it would be like this:

function onRollOut(m:MouseEvent)
{
if(selected) return; // if it’s selected the function will stop in its tracks
doAction();
}

I prefer the latter - because the code is a bit more streamlined.

I know this may seem pretty basic to most of you - but I figured I would put it up here because it was a total eye opener for me at one point.

Happy Coding!
return;

del.icio.us Slashdot Digg Facebook Technorati Google Yahoo


About this entry