41 points · by 3pt14159 · 17y ago · 64 comments
Most of the time when you are writing an if statement, you are comparing a mutable variable to something constant (i.e. variable to string, variable to integer, variable to symbol), so you can avoid the assignment-instead-of-comparison bug by writing constant == variable instead of variable == constant. This way if you forget one of the equals signs you'll get a syntax error. The key with this is you have to get in the habit of doing it and do it all the time, so that you don't have a false sense of security. So instead of:
if foo.to_str == "hi everyone!\n"
puts "hello there!"
enduse
if "hi everyone!\n" == foo.to_str
puts "hello there!"
end if (NULL == ptr) { ..
it throws me off, and it doesn't read as well as the other way around. gcc's -Wall will warn you about it (and I'm sure other interpreters/compilers will do the same). I'd rather let the compiler handle things it's good at and stick to authoring code that's easy to read. if (ptr) {
ptr->foo();
} else {
die();
}
or if (!ptr) {
OhNoes();
}
Also, you can extend the whole lhs-rvalue thing to for loops. Makes them look funny but you get used to it quickly, especially after it helps you avoid a few bugs. for (i = v.begin(); v.end() != i; ++i) {
i->stuff();
}I worked with a C programmer who changed all occurrences of "ptr != 0" to "!ptr". The program stopped working. In Windows, a null pointer is not 0. The C idiom "ptr != 0" compiles correctly, but when you try to get clever with "!ptr", you were in trouble. The expression would evaluate to false on a null pointer. (At least with the version of Visual C++ we were using back then.)
It's only personal preference that leads you to say that, and in this case, for the reasons cited above, it is deeply suboptimal personal preference.
This is a case of Diax's Rake at work.
Fortunately not a problem with Python (the pedantism works!). I still think I prefer Pascal's := for explicit assignment though. Wish more languages would adopt it.
In Java/C# this can throw a null pointer exception:
myString.equals("another string");
however this will never throw anything:
"another string".equals(myString); //false if myString is null, this is what you mean in most cases anyway
I use that like crazy. I'm not sure if Java has something similar now. Years ago when I used java, I remember being constantly frustrated with having to write a helper method in every project to do { return myString==null || myString.equals("");}
I did find "something".equals(myString) helpful though.
if (a != null && a.equals(b))
You can often do:
if (b.equals(a))
I'm sort of reaching here, because I don't know off-hand which language you are using, but I would assume that NULL.equals() would throw an exception. That exception would not be thrown/need to be caught in the first example.
http://c2.com/cgi/wiki?CompareConstantsFromTheLeft
I've mostly stopped doing it though, because now I usually work in languages that won't let you put an assignment in an if statement, and nobody else really does it.
There's no good reason for it in any language built with exceptions from the ground up, though.
There's in idiom in Lua to have functions return either <true, result> or <false, error message> (as two arguments, not a tuple) - consequently, it's common to say e.g. "status, f = assert(open_resource(arg, arg2))"; if it fails, the assert will fail, and open_resource will provide the error message.
In statically typed languages, returning a union type (e.g. Error | Pass of Result) also works well. Sometimes exceptions are simpler, sometimes not.
Extend this to functions as well.
I had a bug like
if (foo(b == A))
instead of
if(foo(b) == A)
Even most bad compilers warn about this now.
puts 'argh' if a = 'b' warning: found = in conditional, should be ==
<?php
if (false !== ($pos = strpos($haystack, $needle))) {
doSomethingWith($haystack, $pos);
}
?>
I find the constant first notation to be very friendly, btw. It's not as natural when translated into English normally, but in terms of logic, it makes sense to think of the first part of the test condition as its own little predicate: // Generic language
bool matchesMyConstantValue(val) {
return MY_CONSTANT_VALUE == val;
}I find assignment-in-conditional more useful in loops than if's, since you can't just plonk the assignment on the previous line.
"a= b;" instead of "a = b;"
I have been doing this constantly in all C-style languages and derivatives and never had any problems using this. This is probably less invasive that your initial suggestion and preserves readability/the usual style.
[1]: To anybody who knows this, too: I am really, really, really unsure where I read that and it's been about 15 long years since I have been doing it, so any correction is much appreciated.
(Found the link:) http://www.joelonsoftware.com/articles/fog0000000073.html
"Occasionally, you will see a C programmer write something like if (0==strlen(x)), putting the constant on the left hand side of the == . This is a really good sign. It means that they were stung once too many times by confusing = and == and have forced themselves to learn a new habit to avoid that trap."
if value = obj.slow_method
puts value
end
I know I had several bugs from the assignment back in my days of coding C/Java in college, and early in my career as a PHP developer, but I can't recall having an issue with it since programming in Ruby. Perhaps the language flow or best-practices manage to avoid the cases when that bug is possible.1) You shouldn't be able to make an assignment (by itself) in an if and not get a compiler error in most modern languages.
2) It goes against the logical flow. You are checking if a variable is equivalent to a constant, not if the constant is equivalent to your variable. If your code is read by someone else who is unfamiliar with this practice then they may get confused by the illogical flow of everything.
"Read '=' as 'equals'. Read '==' as 'is equal to'"
I made this error much less after picking up that habit.
FWIW, I read = as "set" (the verb "to set") or "assign" or "let".