Is there a way of writing this logic in a single, elegant line of code?
<cfif ThumbnailWidth EQ 0>
<cfset Width = 75>
<cfelse>
<cfset Width = ThumbnailWidth>
</cfif>
Coldfusion 9:
<!--- Syntax: ((condition) ? trueStatement : falseStatement) --->
<cfset width = ((ThumbnailWidth EQ 0) ? 75 : ThumbnailWidth) />
Coldfusion 8 and below:
<!--- Syntax: IIf(condition, trueStatement, falseStatement) --->
<cfset width = IIf((ThumbnailWidth EQ 0), 75, ThumbnailWidth) />
Some will say that IIf() is to be avoided for performance reasons. In this simple case I'm sure you'll find no difference. Ben Nadel's Blog has more discussion on IIF() performance and the new ternary operator in CF 9.
I find your original elegant enough - tells the story, easy to read. But that's definitely a personal preference. Luckily there's always at least nine ways to do anything in CFML.
You can put that on one line (CFML has no end-of-line requirements):
<cfif ThumbnailWidth EQ 0><cfset Width = 75><cfelse><cfset Width = ThumbnailWidth></cfif>
You can also use IIF() Function - it'll do the trick:
<cfset Width = IIf(ThumbnailWidth EQ 0, 75, ThumbnailWidth)>
This construct is a little odd tho' - is more clear I think. The strength of IIF() is that it can also be used inline (it is a function after all). For example:
<img src="#ImageName#" width="#IIf(ThumbnailWidth EQ 0, 75, ThumbnailWidth)#">
This last form is often used to maintain a clean(er) HTML layout while injecting dynamic code.
Like Neil said, it's fine the way it is. If you really want a single line you could make it a cfscript
with a ternary operator, like:
<cfscript>width = (ThumbnailWidth == 0) ? 75 : ThumbnailWidth;</cfscript>
Haven't tested this code, but it should work.
If you are looking for concise code, then you can take it a step further than the other examples, taking advantage of CF's evaluation of non-zero values as true
:
<!--- CF 9 example --->
<cfset width = ThumbnailWidth ? ThumbnailWidth : 75>
<!--- CF 8 and below --->
<cfset width = iif(ThumbnailWidth, ThumbnailWidth, 0)>
Naturally, you'll sacrifice a little clarity, but that's the tradeoff for more compact code.
I personally prefer something more along the lines of this:
<cfscript>
Width = ThumbnailWidth;
if(NOT Val(Width)) // if the Width is zero, reset it to the default width.
Width = 75;
</cfscript>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With