Switch statements are simply a much easier and shorter way of writing multiple if statements. If you have a series of if statements testing to see if multiple values have been met, usually the code becomes cluttered, long, and less manageable. Multiple if statements of this sort would look like this:
if (x==5){
//…
}
if (x==6){
//…
}
if (x==7){
//…
}
In situations such as this, it would be advantageous to use a switch statement. A switch statement is activated with the use of the keyword 'switch' and is contained within a block of braces, just like an if statement. The difference is that instead of having to constantly re-write if statements and have clutters of braces, you need only to write out the word "case" before the value that you're testing for. A switch statement is written like this.
//Switch Statement
switch (x) {
case 1: //Actions ;
break;
case 2: //Actions ;
break;
default: trace(“Try something else.”);
break;
}
//Versus the same functionality, using if/else statements:
if (x==1){
//Actions
} // break
if (x==2){
//Actions
} // break
else{
trace(“Try something else.”);
} // break
It is absolutely vital to include the “break” statements within your switch statement. Otherwise, Flash won’t know when one case ends and another begins, and if one case (condition) is met, then it will not only execute that code, but all of the other code below it, until it encounters a “break;” line. This is often referred to as having a leak, as the code execution "leaks" downward until a break statement is met.
This technique should help to save you substantial writing time, as well as make your code far more readable.
Sunday, April 8, 2007
Subscribe to:
Posts (Atom)