Possible Duplicate:
Conditional styles: if (0 == resultIndex) vs if (resultIndex ==0)
I've seen both in code, and I do not know why one is better over the other, but which do you prefer to use, and why?
Possible Duplicate:
Conditional styles: if (0 == resultIndex) vs if (resultIndex ==0)
I've seen both in code, and I do not know why one is better over the other, but which do you prefer to use, and why?
I would say var==null because it's more like what you would actually say. "If my variable is null..." makes more sense than any variant of "If null is my variable..." or "If nothing is my variable..." etc.
The if(null == var)
practice comes from C, where you could accidentally write if(var = null)
(note the assignment operator), which would compile (since in C everything not 0 is true) but will be a semantic error. So if(null == var)
is a defensive practice, since null
is an lvalue (again C/C++ terminology) and lvalues cannot be assigned to.
In modern languages (particularly in C#) compiler will warn you if you do assignment in if
statement.
var == null is the obvious answer. Why would you check null, if you already know what null is? You have to have something to check, before you can check it, so logical ordering is "object == somevaluewearecheckingfor".
I prefer to use (var==null) myself. It makes more sense to me, since I'm checking "if var is null". The other order comes across when I read it as "if null is var", which never makes sense. I also like how VB.NET makes it quite readable, and makes a check for null different from other comparisons, with "if var is nothing".
Typically I tend to go unknown value then known value when I am comparing two values. That way I know first what I am looking in, giving context to the test. Most languages don't care, but I think some may.
They both have the same functionality and produce the same result. The choice is purely a personal one to make.
I personally prefer the first because "var is null" or "var equals null" reads better than "null is var" or "var is null".
Some people prefer the second and claim it reduces typo-induced bugs because null = var
causes an error while var = null
still compiles. These days, however, compilers issue warnings for this, so I believe it is a moot point.