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

后端 未结 19 2611
爱一瞬间的悲伤
爱一瞬间的悲伤 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 20:05

    I would favor using if(!value) because, depending on the names of the variables involved, the "true" case makes much more sense according to English semantics.

    Consider one of the examples in this MSDN article:

    if(pane.IsChecked)
    

    reads in English as, "If the pane is checked".

    However, if(pane.IsChecked == true) reads in English as "If whether the pane is checked is true". That statement that is far less clear in English than it should be.

    One of the reasons why we don't write C# code in binary is human readability. If you're given the choice between code that flows well when you read it and code that doesn't, side with the one that is more readable. I don't think adding the "== true" makes this example more readable, and MSDN doesn't think so either.

    Granted, this is a rather small example to worry about. But as some of the other answers have indicated, not applying this way of thinking to larger-scale cases can hurt readability.

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