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.
-
Possible duplicate: stackoverflow.com/questions/3021195/…aioobe– aioobe2010年10月29日 07:27:40 +00:00Commented Oct 29, 2010 at 7:27
-
It's called "Yoda conditions" ! :DAurelien Ribon– Aurelien Ribon2010年10月29日 07:28:07 +00:00Commented Oct 29, 2010 at 7:28
-
3You mean, "Yoda Conditions, its called."st0le– st0le2010年10月29日 07:29:54 +00:00Commented Oct 29, 2010 at 7:29
-
4'Most of the developers'. Really? Evidence?user207421– user2074212010年10月29日 07:47:00 +00:00Commented Oct 29, 2010 at 7:47
-
@EJP: Yeah, I don't see it very often at all. Perhaps it's most of the developers in his organization.T.J. Crowder– T.J. Crowder2010年10月29日 07:48:32 +00:00Commented Oct 29, 2010 at 7:48
3 Answers 3
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.
4 Comments
no purpose whatsoever in java
would be slightly wrong....If the someVariable
is a Boolean
, it doesn't throw a compile error...:) You'll need to Yoda that out...but otherwise java cleans up for you. :)if (someVariable == true)
, simply use if (someVariable)
(and of course the !someVariable
instead of comparing to false
). (And the fact you can have an inadvertent assignment supports using that style.) The only time I'd use =
or !=
with booleans would be if I were comparing two variables (not comparing to a constant), and the construct wouldn't help me there. :-)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
.
1 Comment
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"))
{
}
3 Comments
equals
over the years. :-(