5 ms·
What he calls yoda conditions is actually considered best practice in C-like languages, as it will result in a compile time error instead of wrong run time beha
by fhars 16y ago
What he calls yoda conditions is actually considered best practice in C-like languages, as it will result in a compile time error instead of wrong run time behaviour if you forget to type the second equals sign. The name is still funny, but the way he has written it up betrays a certain lack of understanding.
- BrandonM 16y agoShouldn't best practice be to compile with something like "gcc -Wall" instead of making the code less readable?
- philwelch 16y agoYoda conditions, like ternary operators[1], are perfectly readable if you have more than a week's experience working with them IMO. Of course, you also turn all the warnings on. [1] By "ternary operators" I mean "pretty-printed, non-nested ternary operators".
- mgrouchy 16y agoThis is something I learned to do when I first started programming and just continued to do. I didn't think it was that uncommon (I also do this in non c-like languages as well because while it produces a runtime error you won't get incorrect behavior, just breakage).
- jemfinch 16y agoI'm not sure you should instantly jump to thinking the term "yoda condition" is derogatory. Yoda is generally considered positively by most nerds.
- fhars 16y agoIt's not the term I'm objecting to, it is the writeup that sounds like it is inferior to the unsafe alternative.
- neilk 16y agoPerhaps I was unclear -- I and probably over half of HN are familiar with that trick already. However, to my knowledge there was no pithy, memorable name for this practice before. It's a good practice in almost any language, BTW. In scripting languages, the error will either be caught at parse time or maybe at runtime, but at least it will be noticed.
- eru 16y ago> It's a good practice in almost any language, BTW. In any language that's susceptible to this kind of bug, yes. Python and Haskell solve it in different ways.
- raganwald 16y agoWhile neither agreeing nor disagreeing with the style of placing the rval on the left and the lval on the right, I'd just like to point out that another way to avoid these errors is to use immutable variables more often.
- kentosi 16y agoI often see programmers with a C/C++ background enter the Java world using Yoda conditions, where such practices serve no use. I used to work with a guy who insisted on using yoda conditions, "just to be sure". This guy would also make sure he'd "null" out all his variables at the end of the method for the same reason.