Learning ColdFusion 9: Ternary Operator Works Around Implicit Array Bug
Earlier this week, I examined the updated implicit array and implicit struct creation functionality in ColdFusion 9. While they provide awesome functionality, I was a little disappointed to find out that there is still some sort of improper order of operations in which the left-hand variable is being defined before the right-hand expression is evaluated. This can lead to very strange and buggy behavior as in the following example:
<!--- Create a raw string value. --->
<cfset data = "Simple Value" />
<!---
Convert the data variable to an array using implicit
array notation.
--->
<cfset data = [ data ] />
<!--- Output the new data variable. --->
<cfdump
var="#data#"
label="Data[ data ]"
/>
Here, we are converting a simple variable into an array containing the original value. This should work just fine; however, due to the error in order of operations, ColdFusion produces the following data structure:
Clearly, something went horribly wrong.
When I was digging through ColdFusion 9's new ternary operator, I found out that if you use a ternary operator to execute this data transformation, it actually executes properly:
<!--- Create a raw string value. --->
<cfset data = "Simple Value" />
<!---
Convert the data variable to an array using a
ternary operator.
--->
<cfset data = (true ? [ data ] : []) />
<!--- Output the new data variable. --->
<cfdump
var="#data#"
label="Data ? [ data ]"
/>
Here, rather than storing [ data ] directly back into the data variable, we are proxying it through the ternary operator. The "false" statement, [], is never to be used. When we run this code, we get the following CFDump:
As you can see, the simple data value was successfully converted into an array containing the original, simple value. While this might seem rediculous, remember that the condition statement here would most likely be something like:
!isArray( data )
... which would make this much more natural. For a better example, see my post on ColdFusion 9's ternary operator.
This hack does not work with the implicit struct bug; you still end up getting an infinitely nested result.
Now, obviously, the implicit array solution here is not the solution that we ultimately want. Ultimately, we want the final release of ColdFusion 9 to fix the core problem in statement evaluation. But, if you need to overwrite a variable with itself (I found this bug because it's a common use case), this appears to be a reasonable work-around for the time being.
Want to use code from this post? Check out the license.
Reader Comments
Crayz. You must've really had to dig deep to find this one!
@Eric,
Converting data types is something that happens more often than you realize, so when ternary operators came along, it felt like a natural thing to try. But, when I tried it, I was like, "wait! isn't that supposed to break?!?"