1 post tagged “as 3”
At work we recently had an email discussion about the best way to approach compound boolean statements in MXML. The problem is that MXML is a subset of XML, which means that you cannot have certain characters anywhere in your MXML, including &. So if you want to write something like this:
<mx:Canvas visible="{bool1 && bool2}"/>
The MXML parser chokes. There are a few ways around this, however. One approach championed by many here in office is to replace the & with "&" which is the XML representation of an & character. So then your code looks like this:
<mx:Canvas visible="{bool1 && bool2/>
Personally, I don't like this choice. If I read code from someone I didn't know and saw this I would think that they were not a great programmer. Basically it feels like a hack to me -- it seems clumsy and messy. Although
it takes a little more time to write, and perhaps a few seconds longer to read, I think that when compound boolean statements are needed in MXML a better solution is to bind the property to a function that performs the
boolean operation. In any other programming situation this would be an inappropriate use of a function -- merely executing a single boolean statement. But I think that given Adobe's decision to not give us any normal means to include "and" in our conditionals it is a better choice. The code then becomes:
<mx:Canvas visible="{checkMyCanvasVisible(bool1, bool2)}"/>
...
<mx:Script>
...
private function checkMyCanvasVisible(condition1:Boolean, condition2:Boolean):Boolean{
return condition1 && condition2;
}
...
Notice that I pass the relevant variables (bool1 and bool2) as parameters to the function. This causes data binding on those two to function correctly. So my code will execute exactly the same as the other method. If either variable is bindable then the function will be reevaluated for the canvas's "visible" attribute when they are changed. If the function does not take the values as parameters then the function will only be evaluated once and will not update on changes to either variable.
In my opinion this leads to code that is easier to read and maintain. It takes a little longer to write and maybe a little more work to read through since you have to move between MXML and AS code to see everything. But I think that in the end it is easier to understand and maintain than a statement rife with unusual syntax and hard-to-identify operators, especially when dealing with statements that compound several operations. The best solution would be for Adobe to provide us with some alternative keyword (like AND, maybe), but unless that happens I think that moving to functions is the best solution.