Possible Duplicates:
What's the comparison difference?
Null check in Java
Most of the developers have the habit of writing the null checking with null in the left hand side.like,
if(null == someVariable)
Does this help any way? According to me this is affecting the readability of the code.
No, it has no purpose whatsoever in Java.
In C and some of its related languages, it was sometimes used to avoid making this mistake:
if (someVariable = null)
Note the =
rather than ==
, the author has inadvertently assigned null
to someVariable
rather than checking for null
. But that will result in a compiler error in Java.
Even in C, any modern compiler will have an option to treat the if (someVariable = null)
as a warning (or even an error).
Stylistically, I agree with you — I wouldn't say "if 21 you are, I will serve you a drink" (unless I'd already had a couple several and was doing my Yoda impersonation). Mind you, that's English; for all I know it would make perfect sense in other languages, in which case it would be perfectly reasonable style for speakers of those languages.
It used to help in 'the olden days' when C compilers would not complain about missing an =
, when wanting ==
:
// OOps forgot an equals, and got assignment
if (someVariable = null)
{
}
Any modern C#/Java/C++/C compiler should raise a warning (and hopefully an error).
Personally, I find
if (someVariable == null)
{
}
more readable than starting with the null
.
In your case, I don't see any merit in doing that way. But I prefer the following...
if("a string".equals(strVariable))
{
}
over this..
if(strVariable != null && strVariable.equals("a string"))
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With