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>
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>
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.
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 definately 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.
Hope this helps,
Jim Davis
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>