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:

ActionScript
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:

ActionScript
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:

ActionScript
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:

ActionScript
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)

Comments (1)

  1. 17:33, 10. July 2009Larry Emlich  / Reply

    Great idea. I will probably start using this technique and will be monitoring your blog for more. :)

Leave a Reply

Allowed Tags - You may use these HTML tags and attributes in your comment.

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Pingbacks (0)

› No pingbacks yet.