Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't like this... Is this cheating the language?

I have seen something like the following a couple times... and I hate it. Is this basically 'cheating' the language? Or.. would you consider this to be 'ok' because the IsNullOrEmpty is evaluated first, all the time?

(We could argue whether or not a string should be NULL when it comes out of a function, but that isn't really the question.)

string someString;
someString = MagicFunction();

if (!string.IsNullOrEmpty(someString) && someString.Length > 3)
{
    // normal string, do whatever
}
else
{
   // On a NULL string, it drops to here, because first evaluation of IsNullOrEmpty fails
   // However, the Length function, if used by itself, would throw an exception.
}

EDIT: Thanks again to everyone for reminding me of this language fundamental. While I knew "why" it worked, I can't believe I didn't know/remember the name of the concept.

(In case anyone wants any background.. I came upon this while troubleshooting exceptions generated by NULL strings and .Length > x exceptions... in different places of the code. So when I saw the above code, in addition to everything else, my frustration took over from there.)

like image 274
mpeterson Avatar asked May 07 '09 20:05

mpeterson


2 Answers

You're taking advantage of a language feature known as short circuiting. This is not cheating the language but in fact using a feature exactly how it was designed to be used.

like image 56
JaredPar Avatar answered Sep 18 '22 18:09

JaredPar


If you are asking if its ok to depend on the "short circuit" relational operators && and ||, then yes thats totally fine.

like image 23
Mike Kucera Avatar answered Sep 19 '22 18:09

Mike Kucera