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

后端 未结 30 2268
礼貌的吻别
礼貌的吻别 2020-12-02 19:49

I keep seeing code that does checks like this

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

or this

if (IsGood == true)
{
   D         


        
相关标签:
30条回答
  • 2020-12-02 20:30

    I always chuckle (or throw something at someone, depending on my mood) when I come across

    if (someBoolean == true) { /* ... */ }
    

    because surely if you can't rely on the fact that your comparison returns a boolean, then you can't rely on comparing the result to true either, so the code should become

    if ((someBoolean == true) == true) { /* ... */ }
    

    but, of course, this should really be

    if (((someBoolean == true) == true) == true) { /* ... */ }
    

    but, of course ...

    (ah, compilation failed. Back to work.)

    0 讨论(0)
  • 2020-12-02 20:32

    I follow the same syntax as you, it's less verbose.

    People (more beginner) prefer to use == true just to be sure that it's what they want. They are used to use operator in their conditional... they found it more readable. But once you got more advanced, you found it irritating because it's too verbose.

    0 讨论(0)
  • 2020-12-02 20:32

    Readability only..

    If anything the way you prefer is more efficient when compiled into machine code. However I expect they produce exactly the same machine code.

    0 讨论(0)
  • 2020-12-02 20:36

    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)
    {
        ...
    }
    
    0 讨论(0)
  • 2020-12-02 20:36

    Ah, I have some co-worked favoring the longer form, arguing it is more readable than the tiny !

    I started to "fix" that, since booleans are self sufficient, then I dropped the crusade... ^_^ They don't like clean up of code here, anyway, arguing it makes integration between branches difficult (that's true, but then you live forever with bad looking code...).

    If you write correctly your boolean variable name, it should read naturally:
    if (isSuccessful) vs. if (returnCode)

    I might indulge in boolean comparison in some cases, like:
    if (PropertyProvider.getBooleanProperty(SOME_SETTING, true) == true) because it reads less "naturally".

    0 讨论(0)
  • 2020-12-02 20:36

    I do not use == but sometime I use != because it's more clear in my mind. BUT at my job we do not use != or ==. We try to get a name that is significat if with hasXYZ() or isABC().

    0 讨论(0)
提交回复
热议问题