Ternary Operations and CFML

Posted by Mark Drew on code on March 24, 2011

Tagged under railo,coldfusion,cfml

I have been doing a lot of JavaScript development recently and finally got my head round Ternary operations. Something that Railo Server has had for a while and I think was introduced to Adobe CF8 CF9 a while ago too. I just never got round to making it part of my standard coding practices, so I thought I would share.

If you have been doing this for a while, no need to point and laugh at me, but if you haven't, let me explain.

In your code you get to points where you have some code that looks like this:
<cfif MyVar EQ "something"> </cfif> </code> </p>

When I see that, I tend to think, what is the fastest way to do this? What makes more sense? In the code above, in *theory* the variable myResult will always be created, but since it is always created, why have the cfelse statement?

I started coding in this manner subsequently:
<cfif MyVar EQ "something"> </cfif> </code> </p>

This way the myResult variable is always set to a "default" and only modified if the statement becomes true. For some reason this makes me feel happier and that the code is more robust (and of course, there is less of it). </p>

With a ternary operation, you can even reduce ALL that code (omg! 4 lines of code!) into a single line:
<cfset myResult = MyVar EQ "something" ? 1 : 0>

The code above now is all in one line. The whole logic relating to the myResult variable is neatly encompassed in one line. Suddenly I feel so much happier.




comments powered by Disqus