What is the preferred way to write boolean expressions in Java

前端 未结 9 1996
灰色年华
灰色年华 2021-01-18 05:03

I have always written my boolean expressions like this:

if (!isValid) {
  // code
}

But my new employer insists on the following style:

相关标签:
9条回答
  • 2021-01-18 05:10

    Absolutely the first. The second betrays a lack of understanding of the nature of expressions and values, and as part of the coding standard, it implies that the employer expects to hire very incompetent programmers - not a good omen.

    0 讨论(0)
  • 2021-01-18 05:10

    The second style doesn't require you to negate the expression yourself (which might be far more complicated than just "isValid"). But writing "isValid == false" may lead to an unintended assignment if you forget to type two ='s, hence the idiom is to put on the right side what can't be an rvalue.

    The first style seems to be preferred among people who know what they're doing.

    0 讨论(0)
  • 2021-01-18 05:14

    I'm going to attempt a comprehensive answer here that incorporates all the above answers.

    The first style is definitely to be preferred for the following reasons:

    • it's shorter
    • it is more readable, and hence easier to understand
    • it is more widely used, which means that readers will recognize the pattern more quickly
    • "false==..." rather than "...==false" is yet another violation of natural order,which makes the reader think "is there something strange going on that I need to pay attention to", when there isn't.

    The only exception to this is when the variable is a Boolean rather than a boolean. In that case the second is a different expression from the first, evaluating to false when isValid is null as well as when it is Boolean.FALSE. If this is the case there are good arguments for using the second.

    0 讨论(0)
  • 2021-01-18 05:19

    Everybody recognizes this snippet:

    if (isValid.toString().lenght() > 4) {
       //code
    }
    

    I think your second example looks at the same direction.

    0 讨论(0)
  • 2021-01-18 05:22

    I prefer the first style because it is more natural for me to read. It's very unusual to see the second style.

    One reason why some people might prefer the second over another alternative:

    if (isValid == false) { ... }
    

    is that with the latter you accidentally write a single = instead of == then you are assigning to isValid instead of testing it but with the constant first you will get a compile error.

    But with your first suggestion this issue isn't even a problem, so this is another reason to prefer the first.

    0 讨论(0)
  • 2021-01-18 05:24

    You are evaluating the variable, not false so the latter is not correct from a readability perspective. So I would personally stick with the first option.

    0 讨论(0)
提交回复
热议问题