Untyped variables in AS3
Actionscript 3 is typed, but not strongly typed - meaning that you can initialize variables without specifying type and have them implicitly cast at runtime. It’s a well established fact that this is not good programming practice, as it creates ambiguity in code and bypasses type checking, which is an important layer of bug detection. However I have come across a situation where keeping the type ambiguous is not only helpful but positively necessary. The scenario is a button on a Flash form; we want the button to run some code when it is either clicked or activated from the keyboard (by tabbing and then enter). We set up the event listeners like so:
this.btn.addEventListener(MouseEvent.CLICK, this.doClickAction);
this.btn.addEventListener(KeyboardEvent.KEY_DOWN, this.doClickAction);
Now, it’s when we implement the doClickAction() function that we run into a quandary. The mouse click event brings with it an event variable of type MouseEvent; the key press an event variable of type KeyboardEvent. Which should we use in our function signature? Well, if you don’t feel queasy about it, don’t specify the type of the input parameter at all:
public function doClickAction(event):void
{
// blah blah blah
}
Problem solved. Sloppy? Maybe. Useful? Absolutely. I suppose the more correct way might be to use two different functions for the two listeners. But that gets old pretty fast, believe me.
