Do not write if (isAdmin == true) code in Java

Introduction

I think it's natural, but there are times when it's unexpectedly not protected. As an example, let's take the handling of boolean in conditional branching.

~~ I wrote "in Java" in the title, but it's probably the same in any language. ~~ Cancel it because it does not apply to other languages such as JavaScript [^ js].

What's wrong

In some cases, it is clearly denied by the coding standard [^ 1], but in Java, the following code ** should not be written **.

if (isAdmin == true) {
  //When isAdmin is true
}

if (isAdmin == false) {
  //When isAdmin is false
}

I will write three reasons.

Reason 1: Redundant

The above code can be written as: This is simpler.

if (isAdmin) {
  //When isAdmin is true
}

if (!isAdmin) {
  //When isAdmin is false
}

In the case of ʻif ~ else ~`, it may be simple to write with the ternary operator. However, abuse of the ternary operator can reduce readability. Please refer to the following article for details.

String userType;
if (isAdmin) {
  userType = "Administrator";
} else {
  userType = "General";
}

//It is simpler to write with the ternary operator as follows
String userType = isAdmin ? "Administrator" : "General";

If it is true, there is no problem, but if it is false, there are cases where ! Is inconspicuous.

if (!obj.getFoo().isBar()) {
  //processing
}

In such cases, it is a good idea to add an explanatory variable.

boolean bar = obj.getFoo().isBar();
if (!bar) {
  //processing
}

Reason 2: May be mistaken for assignment

In Java, it is decided that the boolean type is written in the if statement, so writing an assignment in the if statement usually results in a compile error. However, in the case of boolean type, even if you write as follows, compilation will pass without warning.

if (isAdmin = true) {
  //When isAdmin is true ... should always be executed
}

if (isAdmin = false) {
  //When isAdmin is false ... it should not always be executed
}

//This will result in a compilation error
if (isAdmin = 1) {
}

However, writing in Yoda notation [^ yoda] as shown below is ** tipping over **.

if (true == isAdmin) {
  //When isAdmin is true
}

if (false == isAdmin) {
  //When isAdmin is false
}

Actually, it will warn you with IDE or FindBugs / SpotBugs [^ 3], so you shouldn't notice it, but if you don't write ʻif (isAdmin == true)` from the beginning, there is no problem.

Reason 3: Slow (in theory)

The following content is only when b == true, and has no effect when using b == false or ! B. See comments for details.

This is almost a digression, but in theory it would be useless [^ 4]. For example, compile the following code and disassemble it with javap -c.

public class Main {
    public int foo(boolean b) {
        if (b == true) {
            return 1;
        } else {
            return 0;
        }
    }

    public int bar(boolean b) {
        if (b) {
            return 1;
        } else {
            return 0;
        }
    }
}

Then you will get the following output (excluding irrelevant output):

  public int foo(boolean);
    Code:
       0: iload_1
       1: iconst_1
       2: if_icmpne     7
       5: iconst_1
       6: ireturn
       7: iconst_0
       8: ireturn

  public int bar(boolean);
    Code:
       0: iload_1
       1: ifeq          6
       4: iconst_1
       5: ireturn
       6: iconst_0
       7: ireturn

If you read this, it will be as follows [^ 5]. I've written it for a long time, but the point is that one instruction is wasted.

Because, ʻif (b) means "if b is true", while ʻif (b == true) means "if b is true when compared to true", which is a roundabout expression. Because it has become.

in conclusion

Some people may say, "I don't care about this," but the accumulation of these small things will make a big difference in the future. I want you to develop good habits little by little.

Postscript

It seems that there was a response, so I will supplement it little by little.

[^ 1]: [Java Coding Conventions – Future Enterprise Coding Standards-Future Architect](https://future-architect.github.io/coding-standards/documents/forJava/Java%E3%82%B3%E3% 83% BC% E3% 83% 87% E3% 82% A3% E3% 83% B3% E3% 82% B0% E8% A6% 8F% E7% B4% 84.html) [^ 3]: [QBA: Method assigning boolean literal value in formula (QBA_QUESTIONABLE_BOOLEAN_ASSIGNMENT)](https://spotbugs.readthedocs.io/ja/latest/bugDescriptions.html#qba-boolean-qba-questionable -boolean-assignment) [^ 4]: I measured it, but I couldn't confirm the difference. So "in theory". [^ 5]: Inferred from The Java® Virtual Machine Specification. [^ yoda]: [Yoda Notation-Wikipedia](https://ja.wikipedia.org/wiki/%E3%83%A8%E3%83%BC%E3%83%80%E8%A8%98%E6 % B3% 95) etc. [^ js]: For JavaScript: Logical Operators-JavaScript | MDN

Recommended Posts

Do not write if (isAdmin == true) code in Java
Write Java8-like code in Java8
[Java] Do not use "+" in append!
Do not declare variables in List in Java
Output true with if (a == 1 && a == 2 && a == 3) in Java (Invisible Identifier)
Do not write 〇〇 logic in Rails View (* added later)
Write flyway callbacks in Java
Java in Visual Studio Code
Guess the character code in Java
Do Scala Option.or Null in Java
Do HelloWorld in Java / IntelliJ / Gradle
Java Spring environment in vs Code
Write test code in Spring Boot
[Rails] What to do if data is not registered in DB
Try an If expression in Java
Let me do VS Code Remote Development + Java development in Proxy environment
Do you use Stream in Java?
How do you write in Scala that was written in Java? (List → Map)
What to do if the prefix c is not bound in JSP
Do not use instance variables in partial
How to do base conversion in Java
Do not accept System.in in gradle run
All same hash code string in Java
Do not return when memoizing in Ruby
Do TensorFlow in Java. It's easy, though. .. .. ..
Add if not in Set, error message if
[Mac] Install Java in Visual Studio Code
In some cases, Java code was nativeized with GraalVM, but it was not accelerated.
What to do if the changes are not reflected in the jar manifest file
[Java] What to do if you get an error in Eclipse saying "Not allowed at source level below 1.X"
Add --enable-preview option in Java in Visual Studio Code
Technology for reading Java source code in Eclipse
Static code analysis with Checkstyle in Java + Gradle
Code to escape a JSON string in Java
Second decoction: Try an If expression in Java
Solution for NetBeans 8.2 not working in Java 9 environment
Try using Sourcetrail (win version) in Java code
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
Try using Sourcetrail (macOS version) in Java code
Write Selenium Java binding code using Silk WebDriver
[AtCoder Problem-ABC001] C-Do wind observation in Java [Code]
How to write Java String # getBytes in Kotlin?
[Java beginner's anguish] Hard-to-test code implemented in Junit
[Mac] Install Java in Visual Studio Code (VS Code)