Описание тега short-circuiting

A feature of some languages to skip certain code at runtime that doesn't affect the outcome, especially when testing compound conditions

When executing code, the result of evaluating of a compound condition - one that is comprised of multiple logical parts, eg A OR (B AND C) - may be known before all parts are known.

For example, if it is known that A is true, the result of evaluating A OR B is true regardless of the value of B. In languages the support it, eg Java, the runtime environment can short circuit the evaluation at some point earlier than the end if the runtime can determine that the overall result will not be affected by any following evaluations within the compound condition.

Generally speaking, short circuits may be made in one of two conditions:

  1. A OR B when A is true (the result is always true)
  2. A AND B when A is false (the result is always false)

This feature gives performance benefits and runtime safety.

Performance

If the second part of the compound condition is expensive to execute, but only relevant if some other condition applies, the expense can be avoided when appropriate. Consider this (java) code:

if (orderObject.isConfirmed() && orderObject.calculateShippingRouteLength() > 1000) {
    display("Your address is too far away");
    return;
}

The expensive call to calculateShippingRouteLength() is avoided unless the order is confirmed.

Safety

Consider what would happen if this java condition was not short circuited:

if (string != null && string.contains("foo"))

If string is null and the evaluation was not short circuited, a NullPointerException would be thrown when the second half was evaluated.