Why use short-circuit code?
Asked Answered
F

9

6

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?

Fribble answered 16/11, 2009 at 20:24 Comment(4)
One note on speed: If you have a halfway decent compiler, it will generate the same machine code for if statements and short circuits. If you don't, it's producing sufficiently bad code that a few extra cycles from some source-level microoptimization will be lost in the noise. Very simply, it's not important.Charlot
@David Would that be true for scripting languages as well?Fribble
@TimLytle in interpreted languages you can have different behaviours due to different parsing and interpretation to be done. Compilers benefit of that to be done before the code has an opportunity of run.Murielmurielle
Control structures give the impression of some action being taken. Short-circuits give the impression an expression is being evaluated. I feel like short-circuits are often used to help the developer know there's nothing really going on, except evaluating a final value (no side effects, etc.)Cognizance
P
4

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...
Pelican answered 16/11, 2009 at 20:42 Comment(0)
E
4

Use it to confuse people!

Eckblad answered 16/11, 2009 at 20:30 Comment(1)
Or perhaps to keep the (easily confused) riff-raff from messing with the code.Spellbind
C
4

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

Cane answered 16/11, 2009 at 20:31 Comment(1)
Less stuff to type makes programmers happy.Correspond
P
4

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...
Pelican answered 16/11, 2009 at 20:42 Comment(0)
H
2

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).

Hershelhershell answered 16/11, 2009 at 20:31 Comment(0)
K
2

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.

Karim answered 16/11, 2009 at 21:20 Comment(1)
That's the 'consolidate nested if statements' I couldn't remember seeing in the past or think up example code.Fribble
S
1

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.

Supernumerary answered 16/11, 2009 at 20:56 Comment(0)
S
0

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.

Spoony answered 16/11, 2009 at 20:29 Comment(2)
Yes, that's one of the examples I cite as having an obvious reason. See the $model->valid() example.Fribble
Exactly. All of the reasons that you cite are very good reasons to use short-circuit evaluation.Spoony
W
0

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.

Wormseed answered 16/11, 2009 at 21:3 Comment(0)
M
0

Think of it this way, if you have a statement like

if( A AND B )

chances are if A returns FALSE you'll only ever want to evaluate B in rare special cases. For this reason NOT using short ciruit evaluation is confusing.

Short circuit evaluation also makes your code more readable by preventing another bracketed indentation and brackets have a tendency to add up.

Marder answered 14/12, 2011 at 19:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.