Using NOT operator in IF conditions
No, there is absolutely nothing wrong with using the !
operator in if..then..else
statements.
The naming of variables, and in your example, methods is what is important. If you are using:
if(!isPerson()) { ... } // Nothing wrong with this
However:
if(!balloons()) { ... } // method is named badly
It all comes down to readability. Always aim for what is the most readable and you won't go wrong. Always try to keep your code continuous as well, for instance, look at Bill the Lizards answer.
It really depends on what you're trying to accomplish. If you have no else clause then if(!doSomething())
seems fine. However, if you have
if(!doSomething()) {
...
}
else {
// do something else
}
I'd probably reverse that logic to remove the !
operator and make the if
clause slightly more clear.
As a general statement, its good to make your if conditionals as readable as possible. For your example, using ! is ok. the problem is when things look like
if ((a.b && c.d.e) || !f)
you might want to do something like
bool isOk = a.b;
bool isStillOk = c.d.e
bool alternateOk = !f
then your if statement is simplified to
if ( (isOk && isStillOk) || alternateOk)
It just makes the code more readable. And if you have to debug, you can debug the isOk set of vars instead of having to dig through the variables in scope. It is also helpful for dealing with NPEs -- breaking code out into simpler chunks is always good.