Using NOT operator in IF conditions

后端 未结 7 1898
遇见更好的自我
遇见更好的自我 2020-12-15 16:10

Is it really a good practice to avoid using NOT operator in IF conditions in order to make your code better readable? I heard the if (doSomething()) is better t

相关标签:
7条回答
  • 2020-12-15 17:12

    As a general statement, its good to make your if conditionals as readable as possible. For your example, using ! is ok. the problem is when things look like

    if ((a.b && c.d.e) || !f)
    

    you might want to do something like

    bool isOk = a.b;
    bool isStillOk = c.d.e
    bool alternateOk = !f
    

    then your if statement is simplified to

    if ( (isOk && isStillOk) || alternateOk)
    

    It just makes the code more readable. And if you have to debug, you can debug the isOk set of vars instead of having to dig through the variables in scope. It is also helpful for dealing with NPEs -- breaking code out into simpler chunks is always good.

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