Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy use short-circuit code?
    text
    copied!<p><em>Related Questions</em>: <a href="https://stackoverflow.com/questions/89154/benefits-of-using-short-circuit-evaluation">Benefits of using short-circuit evaluation</a>, <a href="https://stackoverflow.com/questions/1445867/why-would-a-language-not-use-short-circuit-evaluation">Why would a language NOT use Short-circuit evaluation?</a>, <a href="https://stackoverflow.com/questions/1732403/can-someone-explain-this-line-of-code-please-logic-assignment-operators">Can someone explain this line of code please? (Logic &amp; Assignment operators)</a></p> <p>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?</p> <p>I'm not asking about situations where two entities need to be evaluated anyway, for example:</p> <pre><code>if($user-&gt;auth() AND $model-&gt;valid()){ $model-&gt;save(); } </code></pre> <p>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.</p> <p>This also has a (to me) obvious purpose:</p> <pre><code>if(is_string($userid) AND strlen($userid) &gt; 10){ //do something }; </code></pre> <p>Because it wouldn't be wise to call <code>strlen()</code> with a non-string value.</p> <p>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:</p> <pre><code>defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application')); </code></pre> <p>This could have been:</p> <pre><code>if(!defined('APPLICATION_PATH')){ define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application')); } </code></pre> <p>Or even as a single statement:</p> <pre><code>if(!defined('APPLICATION_PATH')) define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application')); </code></pre> <p>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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload