8 ms·
Even the first example is a bit silly. Nobody is going to not understand that (null == foo) is the same as (foo == null).
by hyperhopper 11y ago
Even the first example is a bit silly. Nobody is going to not understand that (null == foo) is the same as (foo == null).
- a3n 11y agoAgreed. I understand the desire to make the variable of interest more prominent, by putting it first, but that particular bug is well worth defending against.
- bnegreve 11y agoIt does increase the cognitive load for no particular reason. Which is what the author is trying to avoid.
- Freaky 11y agoIt's the difference between, say, length(foo) and foo.length() - any difference in cognitive load should be lost in the noise next to "this variable can be null". And given most languages in use today use = to mean assignment instead of equality, it's hardly "no reason".
- retbull 11y agoExcept if you do if(foo = null){} it won't compile in java which is exactly what you want to happen. So using it in java is just cognitive load and provides 0 benefits.
- lkbm 11y agoHabits are hard to break. Switching back and forth between habits leads to mistakes. There's a trade-off here. I'm not going to say one is definitely worth it vs. the other, but if we pretend the disadvantages of one option don't exist, we lose the ability to make appropriate judgements.
- retbull 11y agoI guess I didn't think about people using C/++ and Java together regularly.
- megous 11y agoAlso, it can still catch bugs even in javascript. It's not related to C at all, as original article states. Equality operator is commutative (sans operand side effects). It's not a quirk.
- szatkus 11y agoIt's easier to use tools or IDE. $ jshint test.js test.js: line 3, col 10, Expected a conditional expression and instead saw an assignment. 1 error
- hire_charts 11y agoIt's easy to call out trivial examples because they're trivial, but you're missing the forest for the trees. His point is that the cognitive load adds up. One (null == foo) probably won't slow you down noticeably, but the more of these tricks and workarounds are scattered throughout, the more time you'll need to spend reading and understanding the code. Sometimes the workarounds are necessary for performance reasons, or they're just good practice to avoid common pitfalls. But in a lot of languages they aren't, so unless you have a good reason for increasing the overhead, it's better to lean towards readability. Edit: Also, for this particular example, a good linter is all you need to warn you about an accidental assignment. If you don't have a linter, sure, then put null first, but it's important to recognize that this sacrifices a small amount of future scannability for the more immediate avoidance of a bug.