From: Lloyd Zusman Date: 2005-11-07T12:25:01+09:00 Subject: Re: programming best practices swille writes: > [ ... ] > > My second question is this. I occasionally see stuff like > if -1 == result > > rather than > if result == -1 > > What, if any, is the benefit of one over the other? > > Thanks Well, the traditional reason is because by putting the number to the left of the comparison, you're protected against the case where you might accidentally type a single equal sign instead of a double: #!/usr/bin/ruby -W0 result = 0 if result = 1 # programmer meant to type "result == 1" puts "one" else puts "not one" end This will print "one", even though "not one" is what is expected. However, if you do the following, the compiler will give you an error: #!/usr/bin/ruby -W0 result = 0 if 1 = result # programmer meant to type "1 == result" puts "one" else puts "not one" end The first case can lead to subtle, very hard to find bugs. The second case won't even compile, so you know right away that there's a problem. Of course, without -W0, you will get a warning in the first case, which helps you see the potential problem. Nonetheless, many people have gotten in the habit of using this little trick, just to be on the safe side. -- Lloyd Zusman ljz@asfast.com God bless you.