开发者

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

开发者 https://www.devze.com 2023-01-14 14:40 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: What is the preferred way to write boolean expressions in Java
This question already has answers here: Closed 12 years ago.

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?.


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

if (!hasPurple) ...


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


I find it a good idea to avoid things like

if (foo == true){}

because occasionally you might write

if (foo = true){}

as a typographical error. Often times it's an easy mistake to spot, but it just seems to lend itself well to making that quick mistake.


When using boolean variable as a condition in statement, don't compare it with true.

Not a mistake, but bad style, As it's already a boolean value, so just use it.

Reasons why "!foo" is better than "foo == false". Referenced from

  • Conciseness: assuming that you are in a context where a boolean is
    required, and "x" is a boolean, it is less characters to write "x" than "x
    == true", or "!x" than "x == false".

  • Convention: seasoned programmers in Java (or C, C++, C# and most other
    languages) expect to see "x" rather
    than "x == true", and "!x" rather
    than "x == false".

  • Robustness: in Java the conditional and loop statements all require a
    boolean valued expression in the
    condition. If "y" is not a boolean,
    then a typo of the form "if (y = foo) {" will give a compilation error in
    Java. But if "y" is a boolean then
    "if (y = foo) {" does not give a
    compilation error. Hence, by avoiding "==" for booleans you avoid setting
    yourself up for a whole raft of bugs
    resulting from typos.


I go for 2 because as a programmer even 2 is readable.

Imagine you have hundreds of such validation check do you always check with false.

No


If you are the only one who is going to maintain your code then you are free to use whatever style you like.

Having said that !foo is favored by most of the developers I know.


Its a matter of opinion. I prefer number 2 because its less code to write and I think it is just as readable.

0

精彩评论

暂无评论...
验证码 换一张
取 消