Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

This is one of the things that I hate most when I see it in someone else's code. I know what it means and why some people do it this way ("what if I accidentally put '=' instead?"). For me it's very much like when a child goes down the stairs counting the steps out loud.

Anyway, here are my arguments against it:

  • It disrupts the natural flow of reading the program code. We, humans, say "if value is zero" and not "if zero is value".
  • Modern compilers warn you when you have an assignment in your condition, or actually if your condition consists of just that assignment, which, yes, looks suspicious anyway
  • You shouldn't forget to put double '=' when you are comparing values if you are a programmer. You may as well forget to put "!" when testing non-equality.
share|improve this question

closed as not constructive by Wonko the Sane, Peter Boughton, Walter, Anna Lear, missingfaktor Nov 5 '10 at 6:17

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

14  
I don't much care for it either, but it is pretty far down my personal list of pet peeves. –  Adam Crossland Nov 4 '10 at 20:19
5  
And programmers do miss the double '=' sometimes. It is an easy mistake to make and one that is very easy to overlook. –  sange Nov 4 '10 at 20:23
7  
How is this not constructive or not a real question? –  TheLQ Nov 5 '10 at 1:36
2  
@TheLQ: ironically, the whole point of the question is: is it constructive to do "Yoda conditionals", so they answered by voting "No, it's not constructive". –  mojuba Nov 5 '10 at 8:08
6  
This is closed so here's my short opinion: how can people remember to write 0 == value but not remember to write ==?? I mean blimey, if you're thinking about it, why not write it correctly to begin with. –  dr Hannibal Lecter Nov 5 '10 at 15:21
show 12 more comments

10 Answers

up vote 37 down vote accepted

Ah, yes, "Yoda conditionals" ("If zero the value is, execute this code you must!"). I always point anyone who claims they're "better" at tools like lint(1). This particular problem has been solved since the late 70s. Most modern languages won't even compile this, as they refuse to coerce the result of the assignment to a boolean.

As others have said, it certainly isn't a problem, but it does provoke a bit of cognitive dissonance.

share|improve this answer
27  
+1 for "Yoda conditionals". I actually LOL'd at that. :) –  Bobby Tables Nov 5 '10 at 0:42
3  
While the ordering is fine, I object to comparison to zero instead of plain boolean cast, if(!value). –  SF. Jul 28 '11 at 7:22
1  
So you consider assignments inside a conditional an error? –  user1249 Nov 10 '11 at 7:05
    
"Most modern languages won't even compile this" The problem comes when you you're using a language that silently coerces the result of the assignment to a boolean. The most popular language that I can think of that does this would be JavaScript. This is why I always use yoda conditionals even in Java so that I don't forget to do it when I'm writing javascript. I switch between the two often enough that it can (and has) been a problem. –  Sam Hasler Dec 1 '11 at 9:47
add comment

Harmful? No. It works either way.

Bad Practice? Debatable, at best. It's simple defensive programming.

Worth losing sleep over? Nah.

share|improve this answer
6  
And when I read it, I understand the code immediately which is to me the most important reason to debate a coding style. I totally agree, not worth losing sleep over. –  Jeff Siver Nov 5 '10 at 4:04
add comment

It is obnoxious because it imposes a small, but noticeable mental tax.

People read left to right in virtually all programming languages (and most natural languages).

If I see 123 == x, the way I mentally parse it is:

  • 123 - so what? incomplete info.
  • == - well, 123 is 123, why test it...
  • x - ok, so that's what we're concerned about. Only now do I have the context.
  • Go back to reconsider 123 and why x is compared to it.

When I see x == 123 mental parsing is:

  • x - Provides context, I know what the condition is about. I may choose to ignore the rest. Based on previous flow I have a good idea why and what's to come (and be surprised if it's different).
  • == - I thought so.
  • 123 - Yup.

The disruption is small (in a simple example), but I always notice it.

Putting the value first may be a good idea if you want to draw attention to it, e.g. if (LAUNCH_NUKES == cmd). Normally this is not the intention.

share|improve this answer
4  
Exactly. In natural languages the constant always comes last for the same reason: if the light is red... –  mojuba Nov 5 '10 at 8:05
1  
@mojuba True, it's almost universal. Oddly, there are a few natural languages where object comes before the subject (OVS/OSV order), but they're all obscure. –  dbkk Nov 5 '10 at 13:42
    
On the other hand, some of us tend to read the symbols before the variable. They're more eye-catching. So I'll parse out = or == before 123 or x, and end up not even bothering to translate the code to English in my head. –  Izkata Jul 9 '12 at 20:16
add comment

This is basically flaimbait.

No, it doesn't do more harm than good. Simple.

More words?

Compiler argument? Erm, ish, maybe - don't put too much faith in the complier to save you from yourself.

"You shouldn't forget" - well duh - no of course you shouldn't meanwhile I'm tired, I've been coding all day I've had to use two different languages and sometimes, just sometimes, being human I make a mistake.

The point of this sort of behaviour is that its defensive, its not there because you expect to make mistakes any more than you have insurance because you expect to crash... but if you do its nice to be covered.

Hard to read? You're complaining that a decent programmer should have == hardwired (which makes all kind of poor assumptions) but that the self same decent programmer can't read 0 == value ??

Does no harm, has potential benefits, silly question, let others do it if they want and move on.

share|improve this answer
5  
I think 0 == value reads unnatural for those who studied algebra way before they studied programming. –  mojuba Nov 4 '10 at 20:32
3  
That's kind of not the point - yes, you're right it doesn't read right but equally a great deal of what we, as programmers, write doesn't exactly stack up as natural language and its a matter of how you interpret what you see –  Murph Nov 4 '10 at 22:03
3  
Bravo.. Not to mention the fact that because it reads unnaturally you are inclined to pay closer attention to it, hence catching potential mistakes. –  mocj Nov 4 '10 at 23:31
5  
@mocj - Therefore, we should all code as obtusely as possible to ensure that people reading our code need to really read our code? –  Kaz Dragon Nov 5 '10 at 10:06
5  
@mocj - I appreciate that, but your argument was that the "brain stutter" as you're reading the Yoda conditional is a good thing. I'm asking the question that, if that is the case, should we aim to write all code so that we cause "brain stutters"? Genuine question. –  Kaz Dragon Nov 5 '10 at 14:44
show 2 more comments

I wouldn't call it harm, but it is obnoxious. So no I wouldn't say it does.

share|improve this answer
add comment

I've never felt that the whole 'what if I forget a =?' ever really held much weight. Yes, you may make a typo, but we all make typos, it seems silly to change your entire coding style because you're afraid of making a mistake. Why not make all of your variables & functions all lowercase with no puncuation, because you might forget to capitalize something or forget an underscore one day?

share|improve this answer
4  
That's not the point of the question, the point is "is it harmful" - and it isn't. A very minor irritation at worst, but not harmful. –  Murph Nov 4 '10 at 20:23
1  
In dynamic languages - absolutely, you may mistype a symbol and waste your time later looking for the source of your bug –  mojuba Nov 4 '10 at 20:24
1  
with all respect, when you've spent a late night (or two) and find the source (in C++ code) is a = instead of ==, it would carry some weight. –  DevSolo Nov 4 '10 at 20:51
1  
@DevSolo: I think that should really happen once or twice in your career, but not more than that –  mojuba Nov 4 '10 at 20:56
add comment

Some people use it to make it clear exactly what a conditional is doing. For instance:

Way 1:

FILE *fp;

fp = fopen("foo.txt", "w+");
if (fp == NULL) {

Way 2:

FILE *fp;

if (NULL == (fp = fopen("foo.txt", "w+"))) {

Some people feel that the second example is more concise, or reversing arguments illustrates the point of a test (conditional) prior to the test itself.

In all actuality, I don't really mind either way. I have my pet peeves about style and the biggest one is inconsistency. So, do it the same way, consistently and I won't mind reading your code.

Mix it up to the point where it looks like six different people with their own distinctive style worked on it at once, I get a little annoyed.

share|improve this answer
2  
The second example made me go "huh?" The first is much more readable. Great example. :) –  muntoo May 1 '11 at 6:43
add comment

The one case where I find it helpful is where the variable part of the if is quite long and seeing the values makes the code easier to read. The dotted namespace languages have the best examples of this.

For example something I worked on with single sign-on had a situation where you could have two concurrent sessions if a certain type of error happened and was recovered a certain way so I have to add a handler for it that was inside an if that looked something like this:

if (2 <= application.httpcontext.current.session["thenameofmysessiontoken"].items.count())

Admittedly in this example there are other ways to do this, but this would be a case where the number-first version is potentially more readable.

share|improve this answer
2  
I think the keyword here is "other ways to do this" ;) –  mojuba Nov 4 '10 at 21:14
    
in this case yes, but in some cases this is still the most readable outcome. My only point is there are some legitimate reasons for doing this other than to combat language or ide behavior and type-o –  Bill Nov 5 '10 at 15:42
add comment

To me, it's simple conditioning. As someone who learned (in the 90's) C and C++, I grew accustomed to it and still use it, even though the reasons are lessoned.

Once you are "conditioned" to look at the left side for the "constant", it becomes second nature.

I also only use it for equivalence (or negated equivalence), not for greater/less than.

I completely agree w/ @Wonko's answer.

share|improve this answer
add comment

And yet the errors occur. And sometimes you want an assignment in a loop operator where you might otherwise check equality, or at least it is standard practice to use it.

I hold with it somewhat.The advice that I have followed ( possibly from Code Complete ) is to keep what should be the lower value on the left in comparisons. I was discussing this with a colleague earlier and he thought it was kind of crazy but I've got very used to it.

So I would say:

if ( 0 <= value )

But I would also say:

if ( value <= 100 )

Equality I will tend to check with the variable on the left though, it's just more readable.

share|improve this answer
1  
I'm used to using if(y > x) all the time. Unless y is a constant. –  muntoo Nov 5 '10 at 0:44
    
I used to do it that way, but once I got the idea of having the lowest values on the left I have found my code is a lot more readable at a glance. –  glenatron Nov 5 '10 at 9:48
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.