Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coding standard for null checking [duplicate]

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.

like image 921
Sujith Avatar asked Oct 29 '10 07:10

Sujith


3 Answers

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.

like image 58
T.J. Crowder Avatar answered Sep 25 '22 04:09

T.J. Crowder


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.

like image 20
Mitch Wheat Avatar answered Sep 23 '22 04:09

Mitch Wheat


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"))
{
}
like image 44
Rosdi Kasim Avatar answered Sep 22 '22 04:09

Rosdi Kasim