DEV Community

Tsuyoshi Chujo
Tsuyoshi Chujo

Posted on

2 3

Do you code `if (foo == true) ` in Java?

There posted the discussion that "Do you code if (foo == true) in Java?" on Qiita, Japanese tech blog.

https://qiita.com/ikemo/items/4f56a283f9e27cf98d81

The auther argues that it's "No" because its verbose (if (foo) is enough), it may cause typo that if (foo = true) and it would increase the number of steps and run slower.

So, the code should be like this.


if (foo) {
    // do something
}

boolean isBuzz = !obj.getFoo().getBar();
if (!isBuzz) {
    // do something
}

Enter fullscreen mode Exit fullscreen mode

and not


if (foo == true) {
    // do something
}

if (obj.getFoo().getBar() == false) {
    // do something
}
Enter fullscreen mode Exit fullscreen mode

However, there posted many counter arguments that ! operator can be easily overlooked, == true is easy to understand, both ways are acceptable, etc.

Basically, I'm for the author's opinion. == true doesn't provide any advantage for readability and simply if (isSuccessful()) is comfortable to pronounce.

How do you think of this?

Thanks.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (4)

Collapse
 
vishnuharidas profile image
Vishnu Haridas • Edited

If you are afraid of if(foo==true) becomes this:

if (foo = true)

then you can always use

if( true == foo)

without any fear.

Collapse
 
bobbypriambodo profile image
Bobby Priambodo

"Fear is the path to the dark side. Fear leads to anger. Anger leads to hate. Hate leads to suffering."

en.wikipedia.org/wiki/Yoda_conditions

:p

Collapse
 
florianschaetz profile image
(((Florian Schätz)))

While we do not need to fear an accidental assignment (if (foo = true) ) in java, I still prefer the short version.

If you use "helper" variables, you can always name them appropriately instead of using !, for example:

boolean isNotBuzz = obj.getFoo().getBar();
if (isNotBuzz) {
...
}

Collapse
 
sam_ferree profile image
Sam Ferree

The name of the variable matters Is it a noun? or a verb/action phrase?

if(bigEndian== true) {
  //Do true stuff
}

if (shouldWait) {
  //Do true stuff
}

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay