I’m working on a java source code that has the style:
if (0 == var) {}
and
if (null == someObj) {}
or
if (0 != var) {}
and
if (null != someObj) {}
Should I rewrite it to:
if (var == 0) {}
and
if (someObj == null) {}
?
Thanks in advance!.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s perfectly valid to have:
It’s famously called yoda condition to prevent accidental use single
=in place of==.I personally never used it. But some people like it. It’s really a matter of taste.
However, it’s of no use in Java. Because, such an accidental typo is caught at compile time.
The following would give a compile time error in Java.
Because assignment operation doesn’t yield Boolean value in Java.
However, in languages like C/C++, the above is valid and compiler would give no errors if warnings are not enabled. The above
ifcondition will always evaluate to false (0) in C/C++. So it may go unnoticed and give unexpected results at run time.In GCC, with all warnings enabled, it would give the warning for the above in C or C++:
So this may not of much use in C/C++ too as one is expected to compile with all warnings and fix all warnings. As I said before it’s a personal choice and makes no difference.
So
if ( 0 == var){}is a valid syntax and is same asif (var == 0) {}and if you prefer Yoda conditions it, go for it!