There are a couple of plausible reasons for this. The first is a hold-over from C. In C:
if(x = NULL) { ... }
... (note single =
) is a mistake some developers might accidentally make.
if(NULL = x) { ... }
... causes a compiler error. So if you're in the habit of putting the null
first, it's harder to make this mistake.
However this logic doesn't apply to !=
, so the only reason to continue putting the null
first is for consistency.
... and in Java if(x = null)
is also a compiler error because Java does not evaluate an assignment into a value.
There is another situation in which putting the "expected" before the "actual" is common, and that is:
if("expected string".equals(string)) { ... }
Because "expected string"
definitely isn't null
, this can't NullPointerException
when string == null
, whereas string.equals("expected string")
would.
So, some programmers get in the habit of putting the expected value first.
My own preference is for something that reads similar to an English sentence, and to me: if(x == null)
is better in that respect.
Some of the tricks we used to do to catch little bugs and typos, are made less necessary by unit-testing habits, by avoiding nulls in the first place, and by judicious use of final
variables.