ColdFusion strikes again

March 21st, 2007

In what must only be possible through the sins of backwards-compatibility, ColdFusion has what must be the most bizarre “trinary operator” of any language I’ve used.


IIf(condition, expr1, expr2)

<cfset a = 1>
<cfset b = 2>
<cfoutput>#IIf(a > b, a, b)#</cfoutput>
--> "2" 

That seems reasonable. What happens if 1 and 2 are strings?

<cfset a = '1'>
<cfset b = '2'>
<cfoutput>#IIf(a GT b, a, b)#</cfoutput>
--> "2" 

Also reasonable – ColdFusion is a weakly dynamically typed language, so 1 is ‘1’. What if the strings aren’t numbers, but text?

<cfset a = 'coolio'>
<cfset b = 'freshmonkey'>
<cfoutput>#IIf(a GT b, a, b)#</cfoutput>
--> Error: variable freshmonkey is undefined (!)

WTF Mate? Diving in a bit more deeply, this is because IIf doesn’t just return the value of expr1 or expr2, it evaluates them. So, of course, there is a solution: the even more bizarre function, DE();

<cfset a = 'coolio'>
<cfset b = 'freshmonkey'>
<cfoutput>#IIf(a GT b, DE(a), DE(b))#</cfoutput>
--> "freshmonkey" 

So how is DE() working it’s magic? Of course, I had to find out:

<cfoutput>#DE('freshmonkey')#</cfoutput>
--> "\"freshmonkey\"" 

Sorry about the escaping.. But yes, that’s right! All DE() does is wrap the expression in double-quotes. Sigh.

Sorry, comments are closed for this article.