How would you write this ActionScript code?
I was just watching Lee Brimelow’s fantastic video about Flash Catalyst and Flash Builder and noticed some Flex / ActionScript code (generated by Flash Catalyst) that caught my attention:
var state:String = currentState;
if ( state == 'closed' ) {
currentState='open';
}
if ( state == 'open' ) {
currentState='closed';
}
This code just toggles the currentState property between ‘open’ and ‘closed’. I initially thought that the code was not very elegant in that form but that maybe there was a reason it was written like that. Maybe Flash Catalyst needs it in that form to understand it. Maybe it’s more efficient for the VM to run. I’m not totally sure. But it made me curious… How would you write the same functionality? Use a ternary operator? A switch statement? If - else if? If - else? And why would you do it that way? Is it your personal preference, are there performance implications, SWF size implications, is your way more readable, or are there other factors? While programming provides us many ways to express our creative freedom it seems that for common patterns like this there might be a universal “best way” to do this. Or perhaps this is just another tabs versus spaces kind of issue. I’d love to hear what the community thinks!