Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice: if(foo== false) or if(!foo) [duplicate]

Possible Duplicate:
What is the preferred way to write boolean expressions in Java

Today, me and my colleague raked up an argument. Which is a better way to use the boolean variables in Java code along with if statements.

boolean foo=true
//1. 

if(foo == false)
    // do something
else
    // do something else

//2.

if(!foo)
    // do something
else
    // do something else

I support [1], since I think it's more readable. What do you guys think?.

like image 920
pavanlimo Avatar asked Aug 30 '10 05:08

pavanlimo


2 Answers

Number 2, along with "foo" having a descriptive name, so that the code reads well:

if (!hasPurple) ...

like image 97
Jeffrey Avatar answered Nov 09 '22 18:11

Jeffrey


I find #2 more readable. I think every Java dev (I'm a C# dev) would know what ! means. I

While probably not the point here, I prefer to put my "true" block as the statement. If the condition is generally going to be false, then I name my variable to represent

if (notFoo) 
  // do something when
else
  // do something else
like image 26
Rob Gray Avatar answered Nov 09 '22 17:11

Rob Gray