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

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

    I would normally prefer if (!value) too, when I know for sure that value is a boolean. But many times it can be a string, or a number.

    The number zero would evaluate to false in conditionals in a lot of languages (not all, though); however, the string "0" would evaluate to true. This is a problem particularly in JavaScript, particularly if you receive JSON strings from the server, particularly if the server is written in PHP (because most PHP developers are careless enough to just take values from the DB and call json_encode on them, not knowing that the DB yields strings and not having a clue that all those zeros and ones that they use as boolean fields will be encoded as strings on the other end, thus all treated as true in conditionals).

    Rant over. My suggestion: be explicit, especially if your language is the “very dynamic” type (i.e. JavaScript, PHP, Perl).

提交回复
热议问题