Prevent using long if-expressions
Hello out there!
Today I learned how to check a lot of statements in one expression, but without having unreadable code like that:
if(this.strChar == 'a' || this.strChar == 'b' || this.strChar == 'c') { .. do something .. }
What you can do instead is creating an unnamed Array, push the values into it and then check if the Array contains one of those values.
Let’s see:
package { pubilc class foo { public function foo(strChar:String = 'default'):Boolean { if(['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'default'].indexOf(strChar) >= 0) { return true; } return false; } } }
i suppose that most of the code should be understandable to you, but let’s take a look at the if-statement:
if(['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'default'].indexOf(strChar) >= 0)
You could also use the following code with the same result:
var arrStringNumbers:Array = new Array(); arrStringNumbers.push('one', 'two', 'three' /*and so on... */); if(arrStringNumbers.indexOf(strChar) >= 0) // give me the index of strChar (if arrStringNumbers does not contain strChar, we get -1 as result, so the if-statement is false)
























Larry Emlich wrotes
am 10. July 2009 @ 17:33
Great idea. I will probably start using this technique and will be monitoring your blog for more.