Should I use `!IsGood` or `IsGood == false`?

2019-01-11 00:31发布

I keep seeing code that does checks like this

if (IsGood == false)
{
   DoSomething();
}

or this

if (IsGood == true)
{
   DoSomething();
}

I hate this syntax, and always use the following syntax.

if (IsGood)
{
   DoSomething();
}

or

if (!IsGood)
{
   DoSomething();
}

Is there any reason to use '== true' or '== false'?

Is it a readability thing? Do people just not understand Boolean variables?

Also, is there any performance difference between the two?

30条回答
Emotional °昔
2楼-- · 2019-01-11 00:45

From the answers so far, this seems to be the consensus:

  1. The short form is best in most cases. (IsGood and !IsGood)
  2. Boolean variables should be written as a positive. (IsGood instead of IsBad)
  3. Since most compilers will output the same code either way, there is no performance difference, except in the case of interpreted languages.
  4. This issue has no clear winner could probably be seen as a battle in the religious war of coding style.
查看更多
倾城 Initia
3楼-- · 2019-01-11 00:45

Cybis, when coding in C++ you can also use the not keyword. It's part of the standard since long time ago, so this code is perfectly valid:

if (not foo ())
   bar ();

Edit: BTW, I forgot to mention that the standard also defines other boolean keywords such as and (&&), bitand (&), or (||), bitor (|), xor (^)... They are called operator synonyms.

查看更多
做个烂人
4楼-- · 2019-01-11 00:46

If you really think you need:

if (Flag == true)

then since the conditional expression is itself boolean you probably want to expand it to:

if ((Flag == true) == true)

and so on. How many more nails does this coffin need?

查看更多
对你真心纯属浪费
5楼-- · 2019-01-11 00:48

The only time I can think where the more vebose code made sense was in pre-.NET Visual Basic where true and false were actually integers (true=-1, false=0) and boolean expressions were considered false if they evaluated to zero and true for any other nonzero values. So, in the case of old VB, the two methods listed were not actually equivalent and if you only wanted something to be true if it evaluated to -1, you had to explicitly compare to 'true'. So, an expression that evaluates to "+1" would be true if evaluated as integer (because it is not zero) but it would not be equivalent to 'true'. I don't know why VB was designed that way, but I see a lot of boolean expressions comparing variables to true and false in old VB code.

查看更多
对你真心纯属浪费
6楼-- · 2019-01-11 00:49

Only thing worse is

if (true == IsGood) {....

Never understood the thought behind that method.

查看更多
对你真心纯属浪费
7楼-- · 2019-01-11 00:49

For readability, you might consider a property that relies on the other property:

public bool IsBad => !IsGood;

Then, you can really get across the meaning:

if (IsBad)
{
    ...
}
查看更多
登录 后发表回答