Search code examples
coding-styleshort-circuitingcode-structure

Why use short-circuit code?


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?


Solution

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