E4X and automatic type conversion

Using E4X can often get confusing. One of the design decisions made in the ECMA spec for E4X is automatic type conversion, which basically means that when you query XML for data, the result might act as if it was XML, XMLList, or String, or heck, even a Number if you throw in the additional automatic type conversions built into ActionScript.

To understand how E4X works, it is useful to remember that E4X is always querying the data. E4X is in fact searching the data for nodes and attributes, either by name or based on boolean rules. The queries can always result in zero or more matches, and the application will not know until a query has been executed. This is why E4X always returns an XMLList, even if there’s only one “hit” for the search. The automatic type conversion then ensures you can use the returned single item list as if it was an XML object.

This sounds all dandy — Flash is after all doing things for you, automatically. We think this is a bad idea though. The problem is that getting data in an unexpected type might break your application, the key word here being might. You never know, for the type conversion is automatic after all.

Here’s a good practice to avoid the worst pitfalls of automatic XML type conversion: Always use the array access operator [0] when you know you are accessing a single XML node in your data using E4X. To see what this means in practice, consider the following E4X statement which returns a list of id attribute values:

configuration.wireframe.house..wall.(uint(@id) == 12).color.@id

…vs. the same, explicitly stating the single nodes accessed on the way:

configuration.wireframe[0].house[0]..wall.(uint(@id) == 12)[0].color.@id

Putting the E4X full of [0]’s looks bad if you consider the readability of code in the same way as you consider the readability of a novel.

But it looks pretty good if you consider that code is more readable, when the workings of the code are clearly stated.

If you’re left wondering, here’s what the above line of E4X does: We know there will be only one company node in our data, so we’re getting that XML node instead of all company nodes. There’s only one maskareas node, too, under the company node, so again, we’re explicitly getting the XML node, not a list of all found maskareas nodes. Then we access all palette descendants, whose id attribute matches 12 (everything you get out of XML is of type String, so @id is typecast into uint to allow for successful comparision). Again we know there’s only one matching palette, so we state in the code we want the first found match, not a list of matches. The last two “words” actually need to match multiple product nodes and their multiple ids.


E4X resources:

Post a Comment

Your email is never shared. Required fields are marked *

*
*