Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I avoid using "!" in if statement in Java?

Tags:

java

Our team's Java Coding Guideline says:

Avoid using "!" in if statement as much as possible.

I have asked other colleagues, but no one gave me clear ideas why, because the guideline was created a long time ago and the author might have left our company.

Do you have any idea?

like image 397
kenju Avatar asked Aug 21 '15 02:08

kenju


People also ask

Is it necessary to use else with if in Java?

No, It's not required to write the else part for the if statement. In fact most of the developers prefer and recommend to avoid the else block.

Are nested if statements bad practice?

The problem only occurs when you have many nested in many and so it can become hard to read and you may forget something, but that's readability, there is nothing wrong in the logic for using nested if statements.


1 Answers

With the information provided, this calls for some speculation. One possible reason is that the intent was not for an if-statement by itself but for an if-else statement. In that case, I can see where you might say that you should reverse the cases so that you don't have the extra operation of the negation. Instead of

if (! boolVar) {
  // Something
} else {
  // Something else
}

you might prefer

if (boolVar) {
  // Something else
} else {
  // Something
}

Whether this is worth it or not is probably more a matter of taste and standardization than anything else.

like image 65
Brick Avatar answered Oct 20 '22 22:10

Brick