What is the preferred way to write boolean expressions in Java

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

提交回复
热议问题