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条回答
forever°为你锁心
2楼-- · 2019-01-11 01:02

We tend to do the following here:

if(IsGood)

or

if(IsGood == false)

The reason for this is because we've got some legacy code written by a guy that is no longer here (in Delphi) that looks like:

if not IsNotGuam then

This has caused us much pain in the past, so it was decided that we would always try to check for the positive; if that wasn't possible, then compare the negative to false.

查看更多
Animai°情兽
3楼-- · 2019-01-11 01:04

For some reason I've always liked

if (IsGood)

more than

if (!IsBad)

and that's why I kind of like Ruby's unless (but it's a little too easy to abuse):

unless (IsBad)

and even more if used like this:

raise InvalidColor unless AllowedColors.include?(color)
查看更多
乱世女痞
4楼-- · 2019-01-11 01:06

Occasionally it has uses in terms of readability. Sometimes a named variable or function call can end up being a double-negative which can be confusing, and making the expected test explicit like this can aid readability.

A good example of this might be strcmp() C/C++ which returns 0 if strings are equal, otherwise < or > 0, depending on where the difference is. So you will often see:

if(strcmp(string1, string2)==0) { /*do something*/ }

Generally however I'd agree with you that

if(!isCached)
{
    Cache(thing);
}

is clearer to read.

查看更多
虎瘦雄心在
5楼-- · 2019-01-11 01:06

The !IsGood pattern is eaiser to find than IsGood == false when reduced to a regular expression.

/\b!IsGood\b/

vs

/\bIsGood\s*==\s*false\b/
/\bIsGood\s*!=\s*true\b/
/\bIsGood\s*(?:==\s*false|!=\s*true)\b/
查看更多
Ridiculous、
6楼-- · 2019-01-11 01:08

You forgot:

if(IsGood == FileNotFound)

查看更多
手持菜刀,她持情操
7楼-- · 2019-01-11 01:10

According to Code Complete a book Jeff got his name from and holds in high regards the following is the way you should treat booleans.

if (IsGood)
if (!IsGood)

I use to go with actually comparing the booleans, but I figured why add an extra step to the process and treat booleans as second rate types. In my view a comparison returns a boolean and a boolean type is already a boolean so why no just use the boolean.

Really what the debate comes down to is using good names for your booleans. Like you did above I always phrase my boolean objects in the for of a question. Such as

  • IsGood
  • HasValue
  • etc.
查看更多
登录 后发表回答