These days lots of codes look like following
if (null==a) {
...
}
which made me a little bit confused "Why?".
I searched internet and found some clue. (BTW, it is called "Yoda Conditions")
Old style C couldn't prevent you from mistyping "=" instead of "=="
Think about it. If you typed "if (a=null) …" where you really meant "if (a==null) ..", it's hard to find bug in the code since it compiles fine.
By reversing it like "if (null=a) .." will cause obvious compile error and we can catch the problem earlier.
C++ has operator overloading
If operator== was overloaded and it can cause infinite loop since the a::operator== will be called again.
See my other posting under generic programming menu.
Early termination
When we do "if (aVar==null)", aVar will be evaluated unnecessarily. Imagine that if aVar has property of other class object and recursively and so on.. All we want to know is simply whether aVar is null. It's more obvious when we're comparing something with equals() method. Object.equals() method can be overridden anytime and it's not guaranteed to act like we expect. Similarly, lots of codes are like
if ("YES".equalsIgnoreCase(answer)) {
...
}
We can guess why. It will easily prevent null pointer exception which can happen by
if (answer.equalsIgnoreCase("YES") {
...
}
when answer was null.
References
- Yoda Conditions, http://en.wikipedia.org/wiki/Yoda_Conditions
- What are yoda conditions, http://united-coders.com/christian-harms/what-are-yoda-conditions/
- New Programming Jargon, http://www.codinghorror.com/blog/2012/07/new-programming-jargon.html