问题
Throughout my (short) career so far in programming (merely a student working on internship) I have noticed that when it comes to IF statements, there is two different ways of doing it.
If we take foo
as a boolean value:
if(foo)
{
//do stuff
}
This is my preferred way of doing things when dealing with IF statements, if I'm looking for false I use:
if(!foo)
{
//do more stuff
}
However, when some people see this they raise an eyebrow, suggesting that I may be stuck in a bad habit. But I wanted to know, is there any difference between this way or the "typical" way?
if(foo == true)
{
//do a bit more stuff
}
Am I falling into a common trap for new programmers? Or is there no difference (at least a noticeable one)
回答1:
I never write == true or == false. It goes against the point of an if-sentence, in my opinion.
an if is basicly: If a Boolean expression is true, do something. a Boolean is a boolean expression in and of itself, so why wrap it?
So in my opinion, the ones using == true are the ones with a bad habit. Becuase they display ignorance of how the language works.
think of these "allowed" ways to write if (Foo) and if (!Foo):
if (Foo == true) //If Foo is the same as true
if (Foo != true //If Foo is not the same as true
if (Foo != false) //if Foo is not the same as false
if (Foo == false) //If Foo is the same as false
if (Foo) //If Foo
if (!Foo) //If not Foo
using == and != with booleans actually introduce new ways to make mistakes both when programming and reading code.
Boolean and !Boolean is hard to misread.
回答2:
I guess doing it your way is recommended in most of the languages
if(foo)
{
//do stuff
}
For instance Python PEP8 says
Don't compare boolean values to True or False using ==.
Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
Another example from Code Conventions for the Java Programming Language 7
The if-else class of statements should have the following form:
if (condition) {
statements;
}
Just the small tip: Speaking about condition checks, here's the good tip I've heard few weeks ago If you compare for instance in C like
if(variable == "value") ....
you can get to the problems that if you write by accident if (variable = "value") ...
compiler will not throw an error, so some people use the convention of if ("value" == variable) ...
, then if you write by accident =
instead of ==
, compiler will throw an error
回答3:
Most coding conventions tell you that boolean checks are tested as
if(someBoolean) {
or
if(!someBoolean) {
This simply improves readability. If you are unsure, check out some code conventions, here are the Java ones for you: http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html
回答4:
Checking if(foo == true)
means
check if foo is equal to true is equal to true
Which is just an overhead according to me.
来源:https://stackoverflow.com/questions/14976344/is-there-a-right-or-wrong-practice-when-using-if-statements-iffoo-or-iffoo