April 8, 2014
Language Enhancements in ColdFusion Splendor – Elvis operator
Comments
(12)
April 8, 2014
Language Enhancements in ColdFusion Splendor – Elvis operator
Newbie 8 posts
Followers: 0 people
(12)

The Elvis operator (?:) is a small but elegant feature added in Splendor. I am going to show you how it shortens your conditional code and  makes it look simpler. But before I get into the details, here is the list of language features added in ColdFusion Splendor.

The Elvis operator assigns the ‘right default’ for a variable or an expression. In an expression, if the resultant value is not defined, then the object will be assigned to the left most part of the expression otherwise a default value (define at the right most part) will be assigned.
Consider a conditional case where the displayname is populated with username variable, if the later is defined otherwise a default value “anonymous” needs to be assigned to the displayname variable. The code snippet shown below display both the syntaxes: one with Elvis operator and other without it:
 
Without Elvis
<cfscript>
   if(isdefined('username')){
       displayName = username;
   }
   else {
    displayName = "anonymous";
   }
</cfscript>

With Elvis operator

   displayName = username ?: "anonymous";

The support for Elvis operator has been provided for function calls and expressions too. Some of the expression cases are: 

 securityNumber = securityStruct[‘Joe’] ?: -1;  // Retrieving from a struct
 colourCode = colourArray[index] ?: "black";   // Retrieving from an array
 employeeName = getEmployeeName(ID) ?: “Joe”;  // A function call
12 Comments
Apr 10, 2014
Apr 10, 2014

@Henry, that ?: example just shows how the Adobe guys don’t actually understand how the null coalescing operator is supposed to work, and have ballsed it up.

See: http://cfmlblog.adamcameron.me/2014/02/coldfusion-11-good-stuff.html#nullCoalescingOperator


Adam

Like
()
Edit
Apr 10, 2014
Apr 10, 2014

@James yes, but the use case is too similar.

However, I just checked out http://www.raymondcamden.com/index.cfm/2014/4/10/Recording-and-demos-from-my-ColdFusion-11-presentation and his sample demonstrates elvis operator much better.

displayName = encodeForHTML(url.name) ?: “Anonymous”;

Without the magic of the new elvis operator, it would have thrown undefined at the encodeForHTML call. It’s like adding a big hidden try/catch for the expression before the operator.

Like
()
Edit
Apr 10, 2014
Apr 10, 2014

I think it is a little different. The changes the username, whereas the Elvis operator does not

Like
()
Edit
Add Comment