Which is clearer form: if(!value) or if(flag == value)?

后端 未结 19 2621
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-23 19:07

I understand this is a subjective question, so I apologize if it needs to be closed, but I feel like it comes up often enough for me to wonder if there is a general preferen

相关标签:
19条回答
  • 2020-12-23 19:40

    I favour the if (!value) style at least for evaluating variables or common properties like Page.IsPostback and the like. For anything more complex I tend to parenthesise the expression like thus:

    if (!(SomeType.SomeProperty.CallingAMethod(input).GetSomething.BooleanProperty))
    

    Just to draw a little more attention to it.

    All in all, it's an argument for Perl-style unless and until keywords.

    0 讨论(0)
  • 2020-12-23 19:42

    I use Not value when coding in VB but tend to use value == false when coding in C#. I find that the exclamation point can sometimes be lost in the name of the variable (e.g. !legal). Maybe it's because I'm, uh, a seasoned veteran.

    0 讨论(0)
  • 2020-12-23 19:44

    I am also of the opinion that using == inside an if is redundant and I have another suggestion, at least visually, by introducing spaces:

    if ( ! created)
    

    Even using OpenDyslexic as font, the not sign ! next to the opening bracket ( can be too close to distinguish it at a glance if(!created).

    0 讨论(0)
  • 2020-12-23 19:45

    I actually many of forms possible.

    This is not actually how it is written to standards, but this is how I see it:

    //if foo is(or exists)
    if(foo)
    
    //if foo is true
    if(foo == true)
    
    //if foo doesn’t exist
    if(!foo)
    
    if foo is false
    if(foo == false)
    

    Hence I don’t see == false is redundant.

    0 讨论(0)
  • 2020-12-23 19:48

    I use if (value == false) The ! in if (!value) is so small I sometimes miss it.

    0 讨论(0)
  • 2020-12-23 19:51

    If the condition is just a check of a single value, then !value is quicker.

    However, when the condition contains multiple value checks, I find it much easier to read value == false. Somehow it is easier to parse multiple checks for equality than multiple negations of values.

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