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?
if (false) means peace of code which is never executed. If some of your code is unused you should remove it.
So the statement " a equals 5 or a equals 7" is true. The || operator can only be used, in Java, where a boolean (true or false) expression is expected, such as in an if statement like the above. So pretty much in an if or a conditional operator (that ?...: thing, sometimes called the ternary operator).
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?
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()".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With