Elvis operator

Hi all

is there a better way to write this with Elvis operator?

params = rc.keyExists('areaId') ? params.append( { 'areaId': rc.areaId } ) : params;

I expected, like in C:

rc.keyExists('areaId') ?? params.append( { 'areaId': rc.areaId } )

Removing the left expression, if the first condition is false, nothing should happen.

1 Like

Why would you want to use the Elvis operator? The Elvis operator begins with an assignment:

someVariable = someValueWhichMayBeNull ?: defaultValueJustInCase;

So Elvis doesn’t actually fit here.

I think this is a typical use-case for the ternary operator instead. There are certainly shorter alternatives to your ternary code. For example

rc.keyExists('areaId') ? params['areaId']=rc.areaId : true; 

The null coaIescing operator ?? doesn’t seem to exist in JAVA, thus I think it won’t be available in CFML. Personally I would use such operators (elvis, ternary, safe navigation) for pure variable assignments only. As soon as mutation methods come into play, I’d go for the classic if-else clause. But that is just my own opinion, because often I don’t feel to be the brightest to read and understand the code immediately when reading it.

Since the method params.append( data ); is a pure mutation method, it can be used without any reassignment. I’d simply:

// If I want to use the shortest way, I'd do: 
if( rc.keyExists( "areaId" ) ) params.append( { "areaId": rc.areaId } ); // learnt that from Lucee Admin Code :D 

But for pure readability I always like to fully write an if-statement because that makes the whole statement a lot more verbose… you can almost read it as a sentence.

//this is what I like the most, because it's way more verbose. 
if( rc.keyExists( "areaId" ) ) {
   params.append( { "areaId": rc.areaId } );
}

But that is just and purely my own and very personal opinion.

2 Likes