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:
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:
This way the myResult variable is always set to a "default" and only modified if the
With a ternary operation, you can even reduce ALL that code (omg! 4 lines of code!) into a single line:
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.
<cfif MyVar EQ "something">
<cfset myResult = MyVar EQ "something" ? 1 : 0>
Tweet
comments powered by Disqus