3 ms·
I keep seeing "if (some_boolean == true)" and it kind of grates on me.
by _0ffh 3y ago
I keep seeing "if (some_boolean == true)" and it kind of grates on me.
- wizofaus 3y agoIn many languages it's necessary if it's a nullable boolean...
- denton-scratch 3y agoIn PHP, you might need "if (some_boolean === true)". There is a fashion for inverting it: "if (true == some_boolean)", which seems arse-over-elbow to me (I do know why people do that).
- grzm 3y agoThe “literal/constant first” form can be used defensively to avoid mistakenly using the wrong operator for languages that have assignment operators that are similar to equality-test operators. For example, this will cause a syntax error: if (true = some_boolean) While this will silently result in an assignment of true to the some_boolean variable, not intended the equality test if (some_boolean = true) Editor hints and linting can help catch this as well, but those aren’t always available (or weren’t available in the past). I think I first saw this in Code Complete 2. Here’s some more explanation https://softwareengineering.stackexchange.com/questions/74086/if-constant-variable-vs-if-variable-constant#74087 https://softwareengineering.stackexchange.com/questions/7408... Looks like the pattern is sometimes referred to as a Yoda expression.
- deleted 3y ago[deleted]