Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can you do in ColdFusion in a single line?

Tags:

coldfusion

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 image 552
Phillip Senn Avatar asked Dec 16 '09 16:12

Phillip Senn


5 Answers

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.

like image 65
Dan Sorensen Avatar answered Oct 04 '22 10:10

Dan Sorensen


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 image 27
Jim Davis Avatar answered Oct 04 '22 12:10

Jim Davis


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.

like image 23
Pablo Avatar answered Oct 04 '22 11:10

Pablo


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.

like image 43
Dave DuPlantis Avatar answered Oct 04 '22 11:10

Dave DuPlantis


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>
like image 41
Jeff Howden Avatar answered Oct 04 '22 10:10

Jeff Howden