Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

len(x) better or x NEQ "" better in CFML?

Tags:

coldfusion

This

<cfif len(x)>

Or

<cfif x NEQ "">

Which one is more efficient and readable? Function call vs comparing empty string?

like image 504
Henry Avatar asked Jul 28 '11 19:07

Henry


4 Answers

I'm with Scott on this one:

<cfif len(trim(x))>

When you assign a database element to a variable, that has a "Null" value, or a single space, it will pass just the length test, the trim fixes that.

I only use just that if I'm in my own code and I'm positive that my variables have been declared. Often I'm abroad in another programmers problem however, so my test would look like:

<cfif isdefined('x') AND len(trim(x)) gt 0>

As for readability, it's not the prettiest, but it's the most thorough.

like image 187
Dave Ostrander Avatar answered Nov 18 '22 17:11

Dave Ostrander


I use:

 if(len("String"));

I think the code is much cleaner and as they like to say "expressive". With this syntax what you are saying with the code is "if this string has a length" do this where with the opposite your code is "saying if the length of the string is a blank string do this".

I also use ColdFusions loose boolean values for lots of things like in addition:

  if(a + b){
   ...
   }
like image 39
bittersweetryan Avatar answered Nov 18 '22 18:11

bittersweetryan


Personally, I typically use:

len( trim( x ) )
like image 44
Scott Stroz Avatar answered Nov 18 '22 16:11

Scott Stroz


Ryan's on the money and rightfully has the accepted answer.

The consideration I have in situations like this is that positively-phrased expressions are slightly easier to get one's brain around than negative ones, so as far as clarity goes: using len() is better than a negative comparison to an empty string.

Also from a pragmatic point of you, you're most probably wanting to know if you have a string with length, not that the string happens to not be an empty string (if you see the slight semantic difference), so the len() approach will more closely match your actual requirements.

As for doing a trim(): unless it's coming from user input and it's important that whitespace padding is removed, I would not do this. I am a firm believer in "garbage in, garbage out". It's also second-guessing the intent of the data, and I deeply dislike code that doesn't simply do precisely what it's told, no more, and no less.

There are absolutely no real-world considerations relating to performance here, so don't worry about that sort of thing, instead focus on what makes the most readable code that does the job at hand.

like image 2
Adam Cameron Avatar answered Nov 18 '22 18:11

Adam Cameron