Re:How to reduce the cognitive load of your code
by gknoy on Tuesday March 29, 2016 @01:03PM
(#11382924)
I think the point was, that as soon as you are aware that typos of "=" and "==" are common, and hard to catch mechanically, the _habit_ of using the (constant == myvar) pattern can suddenly be seen as having more value as a hedge against human error.
I'd rather write it that way, and then later change it in code review to `(myvar == constant)`, than risk writing it as `(myvar = constant)` and have it sneak through. Granted unit tests might catch this, but perhaps the error is in the unit test. ;)
Re:How to reduce the cognitive load of your code
by kilink on Tuesday March 29, 2016 @02:13PM
(#11383554)
Java if statements only allow boolean expressions, so the thing that the Yoda condition is supposed to protect against isn't even possible. I think this is precisely what the author is talking about, as this style is a totally unnecessary holdover from C.
Re:How to reduce the cognitive load of your code
by vitd on Tuesday March 29, 2016 @01:33PM
(#11383163)
For me the _habit_ of using (constant == mylar) is way harder to get used to than using "=" vs "==", which the compiler will warn me about if I mess it up.
Re:How to reduce the cognitive load of your code
by MereInterest on Tuesday March 29, 2016 @03:41PM
(#11384279)
I would disagree that they are hard to catch mechanically. GCC will warn about it with -Wparentheses, which is included in -Wall.
Re:How to reduce the cognitive load of your code
by hibikir on Tuesday March 29, 2016 @02:27PM
(#11383668)
The example you show is just a bad workaround though: Your real problem there is that you have code that deals with input that can be null, but whose job is not just to get rid of the nullability. Keeping around fields that could be null and looking for ways to do it safely is like forcing everyone to wear radiations suits because you refuse to have laws about where you can keep nuclear materials.
This is why in modern Java, or in Scala, we have Option types (and in old school java, Nullable annotations), which makes trickery like that unnecessary.
I don't think it's necessarily confusing, it's just that usually we tend to think of the elements we're working with (variables, objects, functions, etc...) as taking on values, and so linguistically, we ask "is my thing null?" Not, "is nullness something that applies to my thing?" Hence "thing operation value" is arguably cognitively cheaper than "value operation thing."
So you could argue that it's one of those things that increases cognitive load if you're not used to it. That last bit is important because almost anything no matter how convoluted can become acceptable once it becomes a convention. In java I used to wonder why people did this:
rather than until I got more familiar with NPEs. Now the former seems quite natural.