14 ms·
Yoda conditions
- tasubotadas 7y agoAhh... The good 'ol technique for avoiding NPEs in Java.
- neatcoder 7y agoFor those who are wondering what this refers to, it is writing code like this: "foo".equals(myVar) instead of writing: myVar.equals("foo") which could can cause NullPointerException if myVar is null.
- arpa 7y agoAm I sure pretty any that linter warning a throw can of instead breaking flow the both of reading writing and.
- jerf 7y agoDespite the name, it isn't referring to Yoda's grammar form, it's just reversing things around "and" and "or". If you really have a problem telling that "x == y" is the same as "y == x" I suggest coming to a deeper, more complete understanding of the equality operator as a commutative operator where the order doesn't matter rather than thinking of it as "variable is? value", as so many students clearly pick up accidentally. I've actually noticed one thing about Common Core is that they do try much harder than when I was a kid to not accidentally create that impression; my kid's homework is full of "4 + 3 = ___" followed immediately by "____ = 8 + 2". Still kind of glossing over "=" as a "simplify" operator, but it's still an improvement over when I was a kid when it was really easy to pick up the idea that the "=" operator was actually a function meaning "take the expression on the left and simplify it". (I mean, there's a sense where such students aren't even wrong; it is the rational conclusion from the evidence presented.)
- AllegedAlec 7y ago> Still kind of glossing over "=" as a "simplify" operator, but it's still an improvement over when I was a kid when it was really easy to pick up the idea that the "=" operator was actually a function meaning "take the expression on the left and simplify it". What? No. De '=' sign is very simple: what's written to the left of it is equal to what's written on its right.
- bregma 7y agoThe takeaway that many students have is that the equals sign if equivalent to the -> sign, which definitely implies simplification. I know I was set straight as a university freshman in the 1980s, and I have read many things since about that same confusion. Outside of math it probably doesn't matter. Inside of math it matters a lot. Programming is math.
- jerf 7y agoI just want to confirm this is what I meant. While I wasn't as badly affected as some of my peers, I still remember when I truly realized what equality meant. That occurred in college, and embarrassingly late in college at that (though it was in undergrad at least). I suspect I got some extra cognitive interference from my programming language experience, so non-programmers would hopefully have an easier time of it. And I was solving systems of equations with substitution and doing all the usual things to equations one does in math classes, and to all external appearances I would have looked like I understood equality prior to that. But I didn't. Not fully. In hindsight, the best evidence of this was in physics class, where I was perfectly adequate at taking the provided equations and using them, and I understood their derivation, but I still wasn't all that great at combining them fluidly; F = ma, yes, but it still didn't quite fully register that that meant anywhere I saw an F, in any other equation in which it appeared, I could drop in an ma. It's not that F is "convertable" to ma, or that ma simplifies to F, or that the name of ma is F... it's that they ARE each other, there is no conceivable way you can separate them, there is no conceivably witnessable in any way, mathematically or practically, effect from substituting one for the other, there is only one entity that can be named in various ways. I did not fluidly combine them the way I should. If I had the class to do over again, I would do way better this time, even we could somehow erase my first pass entirely from my mind.
- flanbiscuit 7y agoHaha it took me a second to realize what you did there
- jonny_eh 7y agoA second to realize what you did there it took me.
- canacrypto 7y agoI've found it's better to write normal conditions that are easier to read and leave it to your linter to catch unintended assignments.
- thomasahle 7y agoAre they really easier to read though? A lot of the time which variable being tested is obvious, so it makes sense to put the important information - the value - first.
- jonny_eh 7y ago> so it makes sense to put the important information Both sides of the equality check are equally important.
- TheSoftwareGuy 7y agoI think he should have written "it makes sense to put the non-obvious information first" as it contrasts better with the first part of the sentence
- lukecameron 7y agoPrevious discussion: https://news.ycombinator.com/item?id=13668792 https://news.ycombinator.com/item?id=13668792
- frou_dh 7y agoTreating the symptom: Pollute the codebase with warped code. Treating the cause: Use static analysis.
- dgb23 7y agoAlternatively there are languages, where this problem can't arise at all. In Clojure for example: (= ...) just tests for (actual) equality, while (def ...) assigns a symbol to a value, or (swap! atom f) changes the value of an atom (reference type).
- crdrost 7y agoTreating the cause's cause: use a programming language which makes a distinction between actions and values, so that an action-which-produces-a-boolean is not valid where a boolean is expected. Treating the cause's cause's cause: design your own programming language to be a strongly typed functional or logic programming language that is a descendant of the ideas in XSLT, where the attitude was “the most common thing you do in programming is to map one data structure into another, so let’s build the whole language around making those mappings easy first.” There can now be no confusion. Probably treating the cause's cause's cause's cause is something like “just use Excel for everything, why are you using these other languages?”
- peterwwillis 7y ago> Probably treating the cause's cause's cause's cause is something like “just use Excel for everything, why are you using these other languages?” It's be harder to get things done, but we'd be more certain about them
- keymone 7y agosolution: don't have assignment operator.
- kd0amg 7y agoOr use ML-style reference cells, so that assignment cannot work on two things of the same type.
- imglorp 7y agoOr even use plain old := for assignment to help avoid confusion with ==. I wonder if K & R wanted to save a character for terseness. I mean, these are the guys who said, if they were writing Unix again, would "spell creat with an e." https://en.wikiquote.org/wiki/Ken_Thompson https://en.wikiquote.org/wiki/Ken_Thompson
- frou_dh 7y agoT&R are the originators of Unix and C. Kernighan seems to often unwittingly be given Thompson's achievements!
- deleted 7y ago[deleted]
- pluma 7y agoNow you're thinking with ~portals~ monads.
- jedisct1 7y agoAll linters and C compilers emit a warning when an assignment is made in a condition. There are zero reasons to use that ugly and unnatural Yoda notation in 2019.
- codegladiator 7y agoNot all programming languages !
- na85 7y agoDo compilers for other languages emit the same warning? Because there are fewer and fewer reasons to use C in 2019 as well.
- shultays 7y agoNot all languages allows chained assignment (a=b=c) like c++ does, which is why we have this problem (and probably does not automatically cast them to bool either)
- adrianmonk 7y agoChained assignment isn't the reason. The similarity of the "=" and "==" operators is. Specifically, it's both (1) easy to make a typo where you meant "==" but typed "=" and (2) not easy to visually distinguish the two.
- shultays 7y agoIt is part of the reason. In c++ a=b returns a reference to a to allow chain assignments. And also in c++, most stuff casts to bool automatically when you use them as an if condition. When you have both and make the typo, it gives you a relatively silent bug instead of a compile error. Yea sure, the reason is a typo and easily mistakable operators but the actual reason is the code compiles fine Java for example expects a bool for for if(). if(a=b) is only valid when they are, which is relatively rare. So it is mostly a compile error.
- reallydontask 7y agoInterestingly enough they are needed when comparing to $null in Powershell https://rencore.com/blog/powershell-null-comparison/ https://rencore.com/blog/powershell-null-comparison/
- larntz 7y agoI was going to post this too. I ran into this a year or so ago and now always put $null on the left of a comparison.
- logicallee 7y agoonly tangentially related, but one of the things I miss so much about Perl is that, as in English, you can add an "if" or "unless" clause as an afterthought. $x++ if (!condition); like if you start to increment $x++ and then you realize wait a second I only mean if.... "unless" likewise functions as an "if not". This is such a "natural" way to write. Let's compare what happens if you have the thought to add a "statement modifier" in any other programmer language. you're written your statement, and now you have to go back to the beginning of your line, write your condition, open a brace, go back to the end of the line, and close your brace. Or maybe begin an entire code block, since you can't have it on one line anymore. it is so much less natural. why can't other programming languages have that?
- marcinzm 7y agoThe greatest difficulty with code is not in writing it but in reading it.
- dragonwriter 7y ago<result> if/unless <condition> is pretty common in natural language for good reason. I find it far more readable than prefix, block-form if for the simple case of one-line results with no alternative branch.,
- matthewmacleod 7y agoAgreed. Particularly useful for for constructs like: def do_stuff() return unless stuff_enabled? ... end
- pmontra 7y agoRuby has that. x += 1 if !condition Better as x += 1 unless condition I use them not as an afterthought but by design. This is the Ruby Style Guide about it https://rubystyle.guide/#if-as-a-modifier https://rubystyle.guide/#if-as-a-modifier
- bhaak 7y ago
- deleted 7y ago[deleted]
- FPurchess 7y agoNot to mention 'Pokémon exceptions' (catch all)...
- thomascgalvin 7y agoIn Java at least, you almost can't get away from Pokemoning because of the split between checked and unchecked exceptions. About half of libraries throw checked, and the other half throw unchecked.
- sleavey 7y agoOne example of a large code base that uses this is WordPress (PHP).
- memorysafety 7y agoGood job duplicating that second paragraph of the linked article.
- sleavey 7y agoArgh, sorry I missed that, I skipped over the intro and looked at the examples. EDIT: to be fair, this sentence was added today [1]. Not sure if it would have been there when I opened the tab earlier. [1] https://en.wikipedia.org/w/index.php?title=Yoda_conditions&type=revision&diff=910934321&oldid=910931930 https://en.wikipedia.org/w/index.php?title=Yoda_conditions&t...
- pgt 7y agoWhen your only hammer is C, everything looks like a toe. Is there a shorter way of saying, "the wrong solution to the right problem"?
- kstenerud 7y agoIt should be noted that Yoda conditions originated at a time when compilers didn't warn about accidental assignment, and linters weren't that great or had poor compatibility. More often than not, the first solution to a problem isn't the best, but the best solution would take a lot of tooling fixes. The Yoda condition trick is a relic of the past, well past its usefulness and best left in its grave alongside Hungarian notation, macros for "inlining", #include "blah.c", goto, etc.
- human20190310 7y agoStyle lives on, even after the practical purpose for it is no longer relevant. People keep wearing denim, even if they're not working in a mine.
- OliverJones 7y agoYeah. when hacking C and C++ into this habit I got. It was hard to break when using other languages. I've had a lot of feedback from colleagues that it's harder to read because it's rare. If my colleagues say it's hard to read, that's good enough for me.
- kemiller2002 7y agoI know I'm in the minority, but I honestly never really understood why people get so up in arms about this. People keep saying it's so difficult to read, and I just don't understand why. I know that linters and such can catch this most of the time, but a lot of places I've seen don't use them. (I don't know why, that's a whole other discussion.) It just seems to me that it's something that keeps you from wasting time on silly mistakes should be common place. I really don't understand.
- carapace 7y agoYou must be young, friend. The holy wars that used to rage over just where to put curly brackets... (And then Python came along and was like, "U wot mate?", and there were had little wars over "syntactically-significant indentation" and tabs vs. spaces, and how many spaces... And on, and on...)
- plopz 7y agoJust wait until people realize proportional fonts are actually easier to read than mono-spaced fonts.
- kemiller2002 7y agoOh no, I'm not young. I just find this particular argument makes less sense than all the other types of arguments like this. Bracket placement in some languages is necessary to not have unintended effect. Tabs vs spaces can cause problems with certain ides/editors. I can somewhat understand most justifications as to why people have a certain reason for formatting code in their particular way. You want me to indent 3 spaces instead of 2 in Delphi, because that's the way you've done it, fine. I don't care. But this particular one, I don't get it. I never have. The amount of time that this one particular trick saved me in terms of time and frustration is huge. When you spend 45 minutes tracking down a problem because you assigned 5 (or something) to variable by accident, it almost always leads to a mouse throwing event. When someone comes back and says that seeing 42 == x is too difficult to read even though it can save countless hours, I just don't understand. (not every project has the benefit of having a linter or a compiler that will catch things like this.)
- busterarm 7y agoYoda conditionals are still very popular in the PHP/Wordpress space. I never got used to using them personally.
- memorysafety 7y agoSo I'm writing a unit test. I bet everyone here can correctly guess the language. assert ('Content-Type', 'text/plain') in dupefail.headers assert b"registration denied" in dupefail.body assert "403 Forbidden" == dupefail.status I also happen to pay attention to the linter fart^Woutput: C: 61,11: Comparison should be dupefail.status == '403 Forbidden' (misplaced-comparison-constant) I totally admit my thorough hate of pylint, it hasn't really ever helped me once -- mostly led to more `#pylint: disable=…` garbage in the source. I still force myself to use it, as a duty by fellow... other engineers. But that's an aside. Please, tell me how much more "natural" and "un-ugly" the 3-line snippet would read to you had it the third line assert flipped away from Yoda style, just as pylint suggests. I'm eager to hear you.
- yegle 7y agoThat's why normally you do self.assertEqual() instead of assert. To properly support assert with good error reporting, pytest has to rewrite the byte code. See http://doc.pytest.org/en/latest/assert.html#assert-details http://doc.pytest.org/en/latest/assert.html#assert-details
- np_tedious 7y agoEven with them, I do find it Yoda-like that you are supposed to make the expected value be the first argument
- memorysafety 7y agoLook, I'm trying to humanly argue against the statement "Yoda conditions are unnatural". Nature has no boolean conditions. That statement should instead say "Yoda conditions are unfamiliar (to me)" -- at which point it's way easier to see the statement's applicability limits, and dramatically narrow down its consequences. On the contrary; there're many common contexts where Yoda comparisons looks more "natural", meaning they avoid breaking the surrounding code flow, and bring the important part (the constant) up-front. I even brought up a real-world example. Having read `assert "403 Forbidden" == ` and remembering the context, can't you already guess the RHS (and just skim over it)? Sure you can. Non-yoda loses here. Be aware: you don't have to take a "for/against" side in this debate, as our buggy brains try to in every flame war. Both sides have a point. Familiarize yourself, and decide on case-by-case basis. While we're at it: self.assertEqual() is super-ugly and unnatural, in my judgement. Why am I forced to use _thrice_ as much words to express the simple single-word concept of an assert? Why can't I spare the extra pair of parens, and spell == directly? I see nothing wrong with bytecode rewriting; it's amazing they can do it, and I appreciate the effort.
- johnnylambada 7y agoI use Yoda style string comparations in java all the time since they are null safe. But other than that I wouldn't have much use for them because they're more difficult to read
- logfromblammo 7y agoI once worked for a place that explicitly told me not to do this. They also told me to test booleans with if( booleanVariable == true ) ... This was also the place that ordered me not to use LINQ statements because, and I quote, "you need to write code that someone fresh out of high school could understand". I don't work there any more.
- lnanek2 7y agoWe actually have to write boolean checks like that in Kotlin nowadays in modern Android development. If your variable type is Boolean? instead of Boolean, it is needed to both check if it is non-null and true.
- logfromblammo 7y agoI was also not allowed to use the C# ?? null-coalesce operator. So something like if( nullableBooleanVariable ?? false ) was also forbidden.
- epx 7y agoI liked Pascal's := attribution. I miss it in almost every language.
- jshowa3 7y agoOf course WordPress uses this in their style guide... if modern compilers catch this, it's a waste of time to use this convention.
- timinman 7y agoThanks for that!