Short Circuit Problem when using conditional statements

 Just a little revision to my educational learnings, whenever we are writing the code with conditional statements, we encounter the issue of Short Circuit Problem. This can be avoided to clearly analyze our requirement of the condiition and do consider the SHORT CIRCUIT could result if condition is satsified.


Consider the following example !

PASTED from the following LINK:

https://stackoverflow.com/questions/9344305/what-is-short-circuiting-and-how-is-it-used-when-programming-in-java

Short-circuiting is where an expression is stopped being evaluated as soon as its outcome is determined. So for instance:

if (a == b || c == d || e == f) {
    // Do something
}

If a == b is true, then c == d and e == f are never evaluated at all, because the expression's outcome has already been determined. if a == b is false, then c == d is evaluated; if it's true, then e == f is never evaluated. This may not seem to make any difference, but consider:

if (foo() || bar() || baz()) {
    // Do something
}

If foo() returns true, then bar and baz are never called, because the expression's outcome has already been determined. So if bar or baz has some other effect than just returning something (a side effect), those effects never occur.

One great example of short-circuiting relates to object references:

if (a != null && a.getFoo() != 42) {
    // Do something
}

a.getFoo() would normally throw a NullPointerException if a were null, but because the expression short-circuits, if a != null is false, the a.getFoo() part never happens, so we don't get an exception.

Note that not all expressions are short-circuited. The || and && operators are short-circuited, but | and & are not, nor are * or /; in fact most operators are not.

Comments

Popular posts from this blog

Export Data from AX 2012 - using DIXF (Data Migration Framework)

The virtual path maps to another application, which is not allowed

Agile Management - TFS (Priority, Stack Rank and Severity)