Learning ActionScript 2.0 in Adobe Flash |
|
|
|
| Best Practices and Coding Conventions for ActionScript 2.0 > Formatting ActionScript syntax > Writing conditional statements | |||
Use the following guidelines when you write conditional statements:
if, else..if, and if..else statements. {}) for if statements.
// if statement
if (condition) {
// statements
}
// if..else statement
if (condition) {
// statements
} else {
// statements
}
// else..if statement
if (condition) {
// statements
} else if (condition) {
// statements
} else {
// statements
}
When you write complex conditions, it is good form to use parentheses [()] to group conditions. If you don't use parentheses, you (or others working with your ActionScript 2.0 code) might run into operator precedence errors.
For example, the following code does not use parentheses around the conditions:
if (fruit == apple && veggie == leek) {}
The following code uses good form by adding parentheses around conditions:
if ((fruit == apple) && (veggie == leek)) {}
You can write a conditional statement that returns a Boolean value in two ways. The second example is preferable:
if (cartArr.length>0) {
return true;
} else {
return false;
}
Compare this example with the previous one:
// better return (cartArr.length > 0);
The second snippet is shorter and has fewer expressions to evaluate. It's easier to read and to understand.
The following example checks if the variable y is greater than zero (0), and returns the result of x/y or a value of zero (0).
return ((y > 0) ? x/y : 0);
The following example shows another way to write this code. This example is preferable:
if (y>0) {
return x/y;
} else {
return 0;
}
The shortened if statement syntax from the first example is known as the conditional operator (?:). It lets you convert simple if..else statements into a single line of code. In this case, the shortened syntax reduces readability.
If you must use conditional operators, place the leading condition (before the question mark [?]) inside parentheses to improve the readability of your code. You can see an example of this in the previous code snippet.
|
|
|
|