Skip to main content

Short-Circuit Logic Should be Used in Boolean Contexts

High
reliabilityError Proneness

What is it?

This practice addresses the use of short-circuit logic operators in boolean contexts to ensure only necessary conditions are evaluated.

Why apply it?

Using non-short-circuit logic operators (e.g., | instead of ||) in boolean contexts can lead to serious program errors, as all conditions are evaluated, even if the result can be determined from the first condition.

How to fix it?

Replace non-short-circuit logic operators with short-circuit operators to prevent unnecessary evaluations and potential side-effects.

Examples

Example 1:

Negative

The negative example uses the bitwise OR operator (|), which causes both functions to be evaluated regardless of the result of getTrue().

public class LogicExample {
public static void main(String[] args) {
if (getTrue() | getFalse()) { /* Noncompliant */
System.out.println("Potential logical error.");
}
}

public static boolean getTrue() {
System.out.println("getTrue() was called.");
return true;
}

public static boolean getFalse() {
System.out.println("getFalse() was called.");
return false;
}
}

Example 2:

Positive

The positive example uses the logical OR operator (||). The second function is only called if the first function returns false.

public class LogicExample {
public static void main(String[] args) {
if (getTrue() || getFalse()) { /* Compliant */
System.out.println("At least one condition is true.");
}
}

public static boolean getTrue() {
return true;
}

public static boolean getFalse() {
return false;
}
}

Negative

The negative example uses the bitwise AND operator (&), which evaluates both functions regardless of the result of isConditionTrue().

public class ConditionalCheck {
public static void main(String[] args) {
if (isConditionTrue() & performAction()) { /* Noncompliant */
System.out.println("Logical error, redundant checks performed.");
}
}

public static boolean isConditionTrue() {
System.out.println("Condition checked.");
return true;
}

public static boolean performAction() {
System.out.println("Action performed.");
return true;
}
}

Example 3:

Positive

The positive example uses the logical AND operator (&&). The second function is only called if the first function returns true.

public class ConditionalCheck {
public static void main(String[] args) {
if (isConditionTrue() && performAction()) { /* Compliant */
System.out.println("Both conditions checked and passed.");
}
}

public static boolean isConditionTrue() {
return true;
}

public static boolean performAction() {
System.out.println("Action performed.");
return true;
}
}