5

If you look at

if (!x) {
if (x == false) {

It looks like !x is better, but

if (!isSomething()) {
if (isSomething() == false) {

you can easily oversee the !

What to do? Is there a recommendation?

Daniel Brose
  • 1,394
  • 10
  • 24
Igor Mukhin
  • 15,014
  • 18
  • 52
  • 61
  • Some of the answers in this question address this issue. http://programmers.stackexchange.com/questions/12807/make-a-big-deal-out-of-true – Ishtar Dec 16 '10 at 13:23

4 Answers4

12

The hidden third option is to name your variables and methods properly.

Instead of

if (!isDisabled()) {
    ...
}

use

if (isEnabled()) {
    ...
}

or if you want to check for the negative:

boolean disabled = !isEnabled();
if (disabled) {
    ...
}

or add both methods:

boolean isDisabled() {
    return !isEnabled();
}

Edit: I found this question: Is it bad to explicitly compare against boolean constants e.g. if (b == false) in Java?

Community
  • 1
  • 1
Christoffer Hammarström
  • 27,242
  • 4
  • 49
  • 58
  • +1 yep, I think if you have a function is better to make it that you check if the return value is true more then if it's not false, like: if(isEnabled()){} – Pietro Dec 16 '10 at 13:27
7

I would stick with the notation if (!isSomething()) {. If you or others find it hard to read you can always add a little whitespace around the '!' in order to make it stand out:

if ( ! isSomething()) { or if ( !isSomething()) {

Furthermore, multiple conditional statements can become overwhelming with the following notation

if (isSomething() == false && isSomethingElse() == false && ..),

whereas its alternative is short and succinct. After a while it becomes natural to read the '!' along with the statements as "not isSomething() and not isSomethingElse()".

McStretch
  • 20,495
  • 2
  • 35
  • 40
3

I don't think there is any recommendation that everyone would follow.

Do it your way, personnally, I would choose the if (!isSomething()) style :)

Especially since I already chose the if (!x) style.

LaGrandMere
  • 10,265
  • 1
  • 33
  • 41
2
if ( !isSomething() ) {

would be the best in my opinion. This way you're keeping the character count down, your code is readable and that ! does stick out at the beginning, so just by skimming through code, others can see its intention.

darioo
  • 46,442
  • 10
  • 75
  • 103