[Java] Be aware of short circuits (short-circuit evaluation)

What is a short circuit (short-circuit evaluation)?

Have you heard of short circuit (short circuit evaluation)?

[Logical operators] such as "<< Left side >> << Logical operator >> << Right side >>" (https://ja.wikipedia.org/wiki/%E8%AB%96%E7%90%86%E6 % BC% 94% E7% AE% 97% E5% AD% 90) Suppose there is an expression (logical operator expression). Short-circuit evaluation is to evaluate the right side (second argument) only when the value of the entire expression is not determined at the stage of evaluating the left side (first argument). Short-circuit evaluation-Wikipedia

Java short circuit operators||When&&Is applicable. A logical operator that means "and" or "or" used when performing logical operations. Let's explain in detail what that means.

Sample code

The isEmpty method checks the String type argument and returns the boolean value as the check result. The condition to check is "either null or an empty string", but the logical operator that means "or" is the short circuit operator.||is.

private static boolean isEmpty(String str) {
    if (str == null || str.isEmpty()) {
        return true;
    }
    return false;
}

If the argument str passed to isEmpty is null, the evaluation result of the left side str == null will be true. Since the evaluation result on the left side is true, the evaluation result of the if statement does not change regardless of whether the evaluation result of the right sidestr.isEmpty () is true or false. Therefore, the evaluation on the right side is unnecessary and the evaluation itself is not executed. The evaluation process is skipped. If the argument str is non-null, for example, the right-hand side needs to be evaluated and str.isEmpty () is executed.

When the evaluation results of both sides are confirmed by the evaluation results of the left side, ** short circuit (short-circuit evaluation) ** does not perform unnecessary evaluation of the right side.

Commentary

||For operators, evaluates whether either the left or right side is true. If the left side is true, the right side is not evaluated because the evaluation result cannot be anything other than true depending on the right side. If the left side is false, the evaluation result is true if the right side is true, and if it is false, the evaluation result is false, so the right side must also be evaluated.

The && operator evaluates whether both the left and right sides are true. If the left side is false, the right side is not evaluated because the evaluation result cannot be anything other than false depending on the right side. If the left side is true, the evaluation result is true if the right side is true, and if it is false, the evaluation result is false, so the right side must also be evaluated.

The logical operator calculates the evaluation result by combining the evaluations of both the right side and the left side. However, by using the short circuit operator, it is possible to evaluate only one of them, that is, to simplify the processing at runtime.

Pit of short circuit

If the argument str passed to isEmpty in the sample code is null, the right-hand side str.isEmpty () will not be executed. That is, no NullPointerException occurs during the evaluation of the if statement.

But what if you swap the left and right sides?

private static boolean isEmpty(String str) {
    if (str.isEmpty() || str == null) {
        return true;
    }
    return false;
}

NullPointerException occurs when the left side str.isEmpty () is evaluated. In coding, it may be necessary to consider the evaluation order of the left side and the right side in this way.

Logical operator||When&&がショートサーキットである意識がない場合、左辺の評価によって右辺の評価自体が行われないこWhenも意識できません。 Java logical operators||When&&はショートサーキットであるこWhenを意識してのコーディングが必要です。

Supplement: About the complete evaluation operator

Basically as a logical operator in Java||When&&を使用するWhen思いますが、ショートサーキットではない、左辺When右辺を必ず評価する論理演算子も存在します。|When&is. This is called the full evaluation operator. It is also called complete Boolean evaluation or complete logical evaluation. I've written Java for quite some years, but I've never used it. It's always a short circuit premise.

However, this is limited to languages that have short circuit operators, and conversely, some languages do not have short circuit operators. That's right for VBA. Always evaluate both sides.

The following is an example implementation of the isEmpty method in VBA without the short circuit operator, but the nesting should be deeper to prevent exceptions. In such a language, if you do not return with an early return as in the example below and be careful not to go out the method, the nesting will become deeper and the readability will decrease ... By the way, in VBA, there is no null in the string string type ( Len (vbNullString) result is 0,vbNullString = ""result is True, Null and ʻEmpty` are for Variant type only. ), Collection type.

Function IsEmpty(ByVal list As Collection) As Boolean
    IsEmpty = True
    If list Is Nothing Then
        ' null(State)in the case of
        Exit Function
    End If
    If list.Count = 0 Then
        'When the number of elements is 0
        Exit Function
    End If
    IsEmpty = False
End Function

Recommended Posts

[Java] Be aware of short circuits (short-circuit evaluation)
Things to be aware of when writing Java
Java Servlet should be aware of multithreaded environment
[Java] Things to be aware of when outputting FizzBuzz
[Java Silver] Things to be aware of regarding switch statements
Things to be aware of when writing code in Java
To be aware of easy-to-read code
5 things new programmers should be aware of
[Beginner] Points to be aware of after Java exercises / Inheritance / Abstract method [Note 26]
[Java] Overview of Java
[Rails] When using ajax, be aware of "CSRF measures".
Things to be aware of when using devise's lockable
Be aware of garbage collection and avoid memory leaks
[Java10] Be careful of using var and generics together
I want to be aware of the contents of variables!