6 ms·
Re: "null != variable": 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, object
by msluyter 11y ago
Re: "null != variable":
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:
if ("".equals(str)) {...
rather than
if (str.equals("")) {...
until I got more familiar with NPEs. Now the former seems quite natural.
- gknoy 11y agoI 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. ;)
- vitd 11y agoFor 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.
- kilink 11y agoJava 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.
- MereInterest 11y agoI would disagree that they are hard to catch mechanically. GCC will warn about it with -Wparentheses, which is included in -Wall.
- hibikir 11y agoThe 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.