What is the difference between
if(null==object)
and
if(object==null)
Please give the advantage for using the above.
The difference comes if you accidentally type =
instead of ==
:
if (null = object)
- Compiler error
if (object = null)
- Bug!
In the good old days, compilers would happily let you make assignments inside conditionals, leading to unintentional errors:
if(a = false)
{
// I'll never execute
}
if(b = null)
{
// I'll never execute
}
b.Method(); // And now I'm null!
So some clever developers started putting their constants first in their conditionals:
if(false = a) // OOPS! Compiler error
{
// ..
}
if(null = b) // OOPS! Compiler error
{
// ..
}
So they trained themselves to avoid a whole class of errors. Most modern compilers will no longer let you make that error, but the practice continues.
There is one other advantage to always putting your constants first:
if(myString != null && myString.Equals("OtherString"))
{
// ...
}
can (in .NET, Java, and most languages with an object-based string type) be reduced to:
if("OtherString".Equals(myString))
{
// ..
}
Well, here is something I kind of like... use extensions:
public static class ObjectExtensions
{
public static bool IsNull(this object target)
{
return null == target;
}
}
Now, you can forget about it completely:
if(item.IsNull())
No difference. (null == object) is a practice from C/C++, where "=" is both used as assignment operator, and as comparison operator.
There were too many errors when if (object = null) was used.
Some prefer if (null == object)
so that if you accidentally type =
instead of ==
, you get a compile error instead of an assignment.
Logically, there is no difference.
From an error checking point of view, the first is more desirable because if you miss an equals sign (=
), the compiler will let you know you can't make an assignment to a constant.
In many languages == is the comparison operator = is the assignment operator.
It very easy to type = when you really mean ==.
Therefore the convention of typing constant==variable is preferred.
constant=variable will not compile thus showing you, your error.
variable=constant will compile and will do the wrong thing at runtime.