What is the preferred way to write boolean expressions in Java

前端 未结 9 2076
灰色年华
灰色年华 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: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.

提交回复
热议问题