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
}
and not
if (foo == true) {
// do something
}
if (obj.getFoo().getBar() == false) {
// do something
}
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.
Top comments (4)
If you are afraid of
if(foo==true)
becomes this:then you can always use
without any fear.
"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
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) {
...
}
The name of the variable matters Is it a noun? or a verb/action phrase?