views:

546

answers:

8

Related Questions: Benefits of using short-circuit evaluation, Why would a language NOT use Short-circuit evaluation?, Can someone explain this line of code please? (Logic & Assignment operators)

There are questions about the benefits of a language using short-circuit code, but I'm wondering what are the benefits for a programmer? Is it just that it can make code a little more concise? Or are there performance reasons?

I'm not asking about situations where two entities need to be evaluated anyway, for example:

if($user->auth() AND $model->valid()){
  $model->save();
}

To me the reasoning there is clear - since both need to be true, you can skip the more costly model validation if the user can't save the data.

This also has a (to me) obvious purpose:

if(is_string($userid) AND strlen($userid) > 10){
  //do something
};

Because it wouldn't be wise to call strlen() with a non-string value.

What I'm wondering about is the use of short-circuit code when it doesn't effect any other statements. For example, from the Zend Application default index page:

defined('APPLICATION_PATH')
 || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

This could have been:

if(!defined('APPLICATION_PATH')){
  define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
}

Or even as a single statement:

if(!defined('APPLICATION_PATH'))
  define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

So why use the short-circuit code? Just for the 'coolness' factor of using logic operators in place of control structures? To consolidate nested if statements? Because it's faster?

A: 

What if you had a expensive to call (performance wise) function that returned a boolean on the right hand side that you only wanted called if another condition was true (or false)? In this case Short circuiting saves you many CPU cycles. It does make the code more concise because of fewer nested if statements. So, for all the reasons you listed at the end of your question.

Poindexter
Yes, that's one of the examples I cite as having an obvious reason. See the $model->valid() example.
Tim Lytle
Exactly. All of the reasons that you cite are very good reasons to use short-circuit evaluation.
Poindexter
+3  A: 

Use it to confuse people!

rlbond
Or perhaps to keep the (easily confused) riff-raff from messing with the code.
NVRAM
+4  A: 

I don't know PHP and I've never seen short-circuiting used outside an if or while condition in the C family of languages, but in Perl it's very idiomatic to say:

open my $filehandle, '<', 'filename' or die "Couldn't open file: $!";

One advantage of having it all in one statement is the variable declaration. Otherwise you'd have to say:

my $filehandle;
unless (open $filehandle, '<', 'filename') {
    die "Couldn't open file: $!";
}

Hard to claim the second one is cleaner in that case. And it'd be wordier still in a language that doesn't have unless

Dan
Less stuff to type makes programmers happy.
nos
+2  A: 

I think your example is for the coolness factor. There's no reason to write code like that.

EDIT: I have no problem with doing it for idiomatic reasons. If everyone else who uses a language uses short-circuit evaluation to make statement-like entities that everyone understands, then you should too. However, my experience is that code of that sort is rarely written in C-family languages; proper form is just to use the "if" statement as normal, which separates the conditional (which presumably has no side effects) from the function call that the conditional controls (which presumably has many side effects).

jprete
+4  A: 

For programmers, the benefit of a less verbose syntax over another more verbose syntax can be:

  • less to type, therefore higher coding efficiency
  • less to read, therefore better maintainability.

Now I'm only talking about when the less verbose syntax is not tricky or clever in any way, just the same recognized way of doing, but in fewer characters.

It's often when you see specific constructs in one language that you wish the language you use could have, but didn't even necessarily realize it before. Some examples off the top of my head:

  • anonymous inner classes in Java instead of passing a pointer to a function (way more lines of code).
  • in Ruby, the ||= operator, to evaluate an expression and assign to it if it evaluates to false or is null. Sure, you can achieve the same thing by 3 lines of code, but why?
  • and many more...
JRL
+1  A: 

Related to what Dan said, I'd think it all depends on the conventions of each programming language. I can't see any difference, so do whatever is idiomatic in each programming language. One thing that could make a difference that comes to mind is if you had to do a series of checks, in that case the short-circuiting style would be much clearer than the alternative if style.

regjo
A: 

The truth is actually performance. Short circuiting is used in compilers to eliminate dead code saving on file size and execution speed. At run-time short-circuiting does not execute the remaining clause in the logical expression if their outcome does not affect the answer, speeding up the evaluation of the formula. I am struggling to remember an example. e.g

a AND b AND c

There are two terms in this formula evaluated left to right.

if a AND b evaluates to FALSE then the next expression AND c can either be FALSE AND TRUE or FALSE AND FALSE. Both evaluate to FALSE no matter what the value of c is. Therefore the compiler does not include AND c in the compiled format hence short-circuiting the code.

To answer the question there are special cases when the compiler cannot determine whether the logical expression has a constant output and hence would not short-circuit the code.

Excalibur2000
+2  A: 

Short circuit operators can be useful in two important circumstances which haven't yet been mentioned:

Case 1. Suppose you had a pointer which may or may not be NULL and you wanted to check that it wasn't NULL, and that the thing it pointed to wasn't 0. However, you must not dereference the pointer if it's NULL. Without short-circuit operators, you would have to do this:

if (a != NULL) {
  if (*a != 0) {
    ⋮
  }
}

However, short-circuit operators allow you to write this more compactly:

if (a != NULL && *a != 0) {
  ⋮
}

in the certain knowledge that *a will not be evaluated if a is NULL.

Case 2. If you want to set a variable to a non-false value returned from one of a series of functions, you can simply do:

my $file = $user_filename ||
           find_file_in_user_path() ||
           find_file_in_system_path() ||
           $default_filename;

This sets the value of $file to $user_filename if it's present, or the result of find_file_in_user_path(), if it's true, or … so on. This is seen perhaps more often in Perl than C, but I have seen it in C.

There are other uses, including the rather contrived examples which you cite above. But they are a useful tool, and one which I have missed when programming in less complex languages.

Tim
That's the 'consolidate nested if statements' I couldn't remember seeing in the past or think up example code.
Tim Lytle