TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Yoda Conditions

76 pointsby sloankevover 8 years ago

15 comments

kibwenover 8 years ago
One of the best bugs I&#x27;ve ever seen was in the game Dungeon Crawl Stone Soup. It&#x27;s a roguelike, and a venerable old one at that, so the codebase is quite tangled and convoluted, with logic for everything in every corner. One of the worshippable gods in the game is Xom, god of chaos, whose effects are just as likely to kill their worshipers as to help them (frustrating for those who might actually want to win, but always good for a laugh). And somewhere in the main game loop was some bit of logic that was only ever supposed to activate while the player was actively worshiping Xom. Guess how this was accidentally implemented:<p><pre><code> if (you.religion = GOD_XOM) { </code></pre> This actually made it to the live test server, where player save files are automatically upgraded to the most recent build, so anyone logging in immediately found themselves infallibly worshiping the god of chaos, every single tick of in-game time (renouncement is futile). Chaos indeed!
paolover 8 years ago
Don&#x27;t do this.<p>In languages where accidental assignment is possible (i.e. writing if(a=b) when you meant if(a==b) ), configure the compiler or linter to emit a warning in this situation.<p>For example in C, GCC will complain about this when compiling with -Wall, which you should be using anyway.
评论 #13669387 未加载
评论 #13669780 未加载
评论 #13669073 未加载
评论 #13669992 未加载
评论 #13669067 未加载
评论 #13669587 未加载
评论 #13669105 未加载
评论 #13670734 未加载
thefifthsetpinover 8 years ago
I&#x27;m fond of Yoda conditionals, but not for the commonly cited reasons. Mostly I just like that they promote the interesting&#x2F;unpredictable part of the comparison to the front. I consider the safety from unexpected assignment, from null pointer exceptions, and the Star Wars reference all to be minor perks.<p>Take this example:<p><pre><code> function handle_request($http){ if(&quot;OPTIONS&quot; === $http.request.method){ ... }else if(&quot;GET&quot; === $http.request.method){ ... }else if(&quot;PUT&quot; === $http.request.method){ ... }else if($http.request.method === &quot;POST&quot;){ ... } ... } </code></pre> Did you read <i>$http.request.method</i> four times? I bet not. Some of you may have read it the first time; I wouldn&#x27;t have. But to know that the fourth block handled POST requests I made you read to the end of the line. That makes it harder to scan the code looking for the section that you want to change. In production code that I&#x27;ve seen, the predictable side of a comparison is often quite long.<p>What&#x27;s especially bizarre to me is the reason people give when advocating writing in the last style. Yes, it verbalizes nicely as &quot;Otherwise, if the http request method post, then...&quot; But who internally translates their code to English to understand it? COBOL was designed to read like natural language. Do you enjoy programming in COBOL? If English-like syntax is desirable for code readability, why don&#x27;t modern programming languages prioritize English-like syntax, too?<p>Greek mathematics got stuck because it remained a verbal, pictorial activity, Moslem &quot;algebra&quot;, after a timid attempt at symbolism, died when it returned to the rhetoric style, and the modern civilized world could only emerge —for better or for worse— ... thanks to the carefully, or at least consciously designed formal symbolisms that we owe to people like Vieta, Descartes, Leibniz, and (later) Boole.<p>-- Dijkstra,
selfsimilarover 8 years ago
In PHP I like using Yoda Conditions because there&#x27;s a common idiom of testing assignment in the conditional:<p><pre><code> if ($value = getSomeValue()) { &#x2F;&#x2F; Safely use value } </code></pre> Yoda Conditions defend nicely against accidents when &#x27;=&#x27; and &#x27;==&#x27; can be used legally this way and honestly you get used to reading them pretty quick.
评论 #13670452 未加载
评论 #13669804 未加载
评论 #13671208 未加载
namanyaygover 8 years ago
A lot more of similar programming jargon by Jeff Atwood [1]<p>[1] <a href="https:&#x2F;&#x2F;blog.codinghorror.com&#x2F;new-programming-jargon&#x2F;" rel="nofollow">https:&#x2F;&#x2F;blog.codinghorror.com&#x2F;new-programming-jargon&#x2F;</a>
评论 #13669765 未加载
logfromblammoover 8 years ago
I was once officially reprimanded for using Yoda conditionals. That was at the same place that required this:<p><pre><code> if( booleanVariable == true ) { ... } else if( booleanVariable == false ) { ... } else { &#x2F;&#x2F; Typically, this section would include an exact copy &#x2F;&#x2F; of one of the above sections, as it was 3 years ago, &#x2F;&#x2F; presumably to pad out the SLoC metrics. } </code></pre> That place had its head <i>so far</i> up its own ass....<p>Equivalence is commutative. Please never complain about the order of its operands as &quot;confusing&quot; or &quot;less readable&quot;. It just tells me that you&#x27;re an ass, trying to enforce a coding convention that has no objective reason to exist.
geofftover 8 years ago
I ran across a bug at $dayjob where someone was clearly trying to use Yoda conditions, but messed up differently:<p><pre><code> if &quot;start&quot; == argv[1]: .... else if &quot;stop&quot; == argv[1]: .... else if &quot;reload&quot;: .... else if &quot;status&quot; == argv[1]: .... </code></pre> I think it&#x27;d be harder to make this mistake with the conditions the right way around. (Also, never mind that the equality bug isn&#x27;t even possible in Python.)
评论 #13673319 未加载
koolbaover 8 years ago
A similar but arguably more useful version of this is when you have two variables, one of which may be null. Traditionally you issue an if-condition test using the variable user input as the left operand but switching it handles the null case automatically.<p>Ex:<p><pre><code> Foo SOME_CONSTANT = &lt;something-not-null&gt;; Foo userSuppliedInput = &lt;some-user-input-possibly-null&gt;; &#x2F;&#x2F; This can raise an null pointer exception if (userSuppliedInput.isEquals(SOME_CONSTANT) { &#x2F;&#x2F; ... } &#x2F;&#x2F; This can&#x27;t raise a null pointer exception (assuming isEquals handles nulls properly): if (SOME_CONSTANT.isEquals(userSuppliedInput) { &#x2F;&#x2F; ... }</code></pre>
评论 #13669147 未加载
nayukiover 8 years ago
I would say that the phrase &quot;Yoda conditions&quot; more appropriately describes Ruby&#x27;s alternative form of if-statements:<p><pre><code> if x &gt; 0: y += x </code></pre> versus<p><pre><code> y += x if x &gt; 0</code></pre>
评论 #13669952 未加载
评论 #13670372 未加载
codr4lifeover 8 years ago
Not worth the effort; modern compilers are very helpful with identifying these kinds of slip ups; and they weren&#x27;t really that common to begin with, not common enough to warrant the attention and energy sucked into this never ending argument. It&#x27;s a rule for the sake of having rules, like so many others.
MilnerRouteover 8 years ago
I didn&#x27;t know abut &quot;Yoda conditions,&quot; and thought it was going to be those &quot;reversed&quot; if statements that were so startling when I&#x27;d started coding in Perl.<p><pre><code> $days = 28 if $month eq &quot;February&quot;;</code></pre>
rocky1138over 8 years ago
I don&#x27;t follow this convention, but something I do follow is naming things by type first. This makes it really easy to find in a long list of files in a folder.<p>Example: plantArrowhead, plantGuzmania, plantMarmo vs. arrowheadPlant, guzmaniaPlant, marmoPlant.
alexeizover 8 years ago
Yoda conditions suck. You don&#x27;t compare a constant to a value of a variable to make sure that the constant has a certain value. Such comparison is backwards. Unfortunately it is extremely popular at Microsoft among C++ programmers. They seem to totally lack any sense of style. Sometime in the nineties the enforcement of Hungarian notation throughout the company had a long lasting damaging effect on their psyche they still can&#x27;t recover from after all these years.
pier25over 8 years ago
ESLint has a rule to prevent this.<p><a href="http:&#x2F;&#x2F;eslint.org&#x2F;docs&#x2F;rules&#x2F;yoda" rel="nofollow">http:&#x2F;&#x2F;eslint.org&#x2F;docs&#x2F;rules&#x2F;yoda</a>
oli5679over 8 years ago
Interesting idea this is.