Coding standard for null checking [duplicate] - java

This question already has answers here:
Closed 12 years ago.
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"))
{
}

Related

Best way to check if a reference is null in Java

I was wondring what the best way to check if we have a valid reference in java. I know that this syntax works, but its a mouth full.
if (myObj == null) {
// Do something knowing we have an object
}
I'm coming from some other languages that allow you to just check a pointer like in c++.
char* prt = null;
if (ptr) {
// We know we have a valid c-string
}
Is there any equivocate or similar syntax in java? I would be okay using compiler extensions or a preprocessor.
Follow up before. Before some one jumps in a starts talking about why I should just use the java syntax because you can forget an = sign please don't.
if (myObj = null)
Will be caught by the compiler/linter.
Alas Java does not have an implicit conversion of the analogue of a nullptr_t or a pointer type to bool, so you have to use the somewhat more long-winded notation
if (myObj == null)
whereas in C++ we can write
if (myObj)
In this respect, Java is less terse, and arguably clearer.
There is no shortcut syntax for dealing with null checks in Java, not even a null coalesce or null propagation operators available in other languages. There are no user-defined conversion operators either, so you wouldn't be able to use the C++ idiom that lets you write loops on expressions returning objects, e.g. while (cin >> x) { ... }.
However, a powerful alternative exists in Java 8 to avoid null checks altogether: wrap your nullable objects in Optional<T>, and use its methods to hide null checks.
Here is a short example:
String s = "Hello";
Optional<String> os = Optional.ofNullable(s);
os.ifPresent(x -> { System.out.println(x); });
The above prints "Hello". If you set s to null, the code would print nothing.
Oracle's article on using Optional<T>.
if(x == null) {
doSomething();
}
... is the general idiom in Java. Java's designers made the decision not to allow treating non-boolean variables as implicit "truthy" values.
Another common idiom is to use x == null in a ternary statement:
return x == null ? "not found" : x;
Or to use a standard method to throw an exception early on nulls:
Objects.requireNonNull(x);
More generally, try to adopt a programming style in which you never expect null to be passed, and therefore don't have to code for the possibility.
On non-public APIs, since you never pass a null, you never need to test for null (if a NullPointerException occurs, whoever passed the null can take responsibility for the mess themselves).
In public APIs, it may be a courtesy to the caller to validate non-nulls at the point they are passed, but it's by no means essential in every case.
A reasonable goal is to always expect inputs to be non-null, and to never return a null (since Java 8, use Optional instead if necessary, or adopt the Null Object Pattern).

Which is better way of having a null check?

I came across these two ways of having a null check for a string object.
Given a string object String str = "example";
If(str.someMethod() != null ) or
If (null != str.someMethod())
Why do we prefer the 2nd one ?
What is the exact reason behind this, is it related to performance ?
In your example, it makes absolutely no difference which you do (other than style), because the reason for Yoda checks is to avoid accidentally doing an assignment (but keep reading for why this doesn't matter in Java), and you can't assign to the result of calling a method.
One of the nice things about Java is that even if you were testing str, e.g.:
if (str == null)
vs.
if (null == str)
there would still be no difference, whereas in some of the languages with syntax derived from B (such as C, C++, D, JavaScript, etc.), people do the second (a "Yoda test") to minimize the odds of this bug:
if (str = null) // Not an issue in Java
In C or JavaScript, for instance, that would assign null to str, then evaluate the result, coerce it to boolean, and not branch. But in Java, that's a syntax error the compiler tells you about.
Java doesn't do that kind of boolean conversion, so the only reason for using Yoda checks in Java is if you're testing booleans, e.c.
boolean flag;
// ...
if (flag == false)
There, you might conceivably do this by accident:
if (flag = false)
But since using == and != with booleans is completely unnecessary (you'd just use if (flag) or if (!flag)), in the real world you don't need Yoda checks with Java at all.
That doesn't mean people don't still use them, as a matter of their own personal style. There's just no objective reason to, in Java.
It makes no difference performance-wise, however the Yoda programming pattern have some advantages when it comes to the world of programming skills.
In your example it would not matter as both cases would throw a NullPointerException (since you're invoking someMethod` of a null instance reference).
However, say that you wanted to check if str is null. In the first case, you'd write if (str == null) and in the second if (null == str). Both are the same. Now say that you have accidently used = instead of ==. In Java, it would not matter as the compiler wouldn't let you as the expression doesn't evalute to a boolean value. But other languages let you do that, more specifically languages that are compiler-free and only use an interperter. In that case, if you write if (str = null) you'll be assigning null to string and overriding its' current value, which would result in buggy behavior and you chasing after your tail for quite some time. However, if you'd write if (null = str) you'll get an error saying you cannot assign a value to null and thus save yourself a lot of time and effort. Again, this is not relevant to JAVA.
An example which might be relevant for Java, is the use of method invocation on constant values. For example, if (str.equals("constantString"). If str is null you'll get a NullPointerException. However, if you use a Yoad pattern and write if ("constantString".equals(str)) you'll get false as ConstantString does not equal null. This of course is only relevant for comparison, and not say contains etc.

null == foo versus foo == null [duplicate]

This question already has answers here:
Which is more effective: if (null == variable) or if (variable == null)? [duplicate]
(9 answers)
Closed 9 years ago.
This may just be a style question, but I'm reading a Java coding book ('Programming Android') and the writer all declares null first before a variable method, a practice I am not familiar with. For example:
if (null == foo) {
//code here
}
or
if (null != foo) {
//code here
}
instead of
if (foo == null) {
//code here
}
I can't see how the order would make a difference semantically/syntactically, or am I wrong here? Really just curious.
It's probably a habit left over from C/C++. In C, you would put constants on the left, because if you mistyped = instead of == there would be an error because you can't assign something to a constant. In Java, this is unnecessary because if (foo = null) also gives an error, which says that an object reference isn't a boolean.
This is a holdover from C/C++. It was advantages to put the value on the left of the == operator in case you accidently used the assignment = operator. The C compiler will catch the 14 = var as an error, but var = 14 will compile, when you meant to type var == 14. There is not much reason to do this in Java, but some still do it.
Sometimes order saves you from null pointer exception e.g. if a String variable is coming from somewhere and you compare it like this:
if(foo.equals("foo")){
}
then you might get Null pointer exception. On the other hand if you do it like this:
if("foo".equals(foo)){
}
then you not only achieve your purpose but you also avoid a null pointer exception in case String foo was null.
No difference.
Second one is merely because C/C++ where programmers always did assignment instead of comparing.
E.g.
// no compiler complaint at all for C/C++
// while in Java, this is illegal.
if(a = 2) {
}
// this is illegal in C/C++
// and thus become best practice, from C/C++ which is not applicable to Java at all.
if(2 = a) {
}
While java compiler will generate compilation error..
There is no really different between two form. There is no performance issue but there are following notes:
First form is readable for code reader, because people usually read
codes Left-To-Right.
Second form is better for code writer, because in java = operator is
for assignment and == operator is for test equivalent, but people
usually using in if statement = instead of ==, by second approch
developer getting Compile-Time-Error because null can't use in
Left-Side of a assignment statement.
ADDED
if (object = null) {
The convention of putting the constant on the left side of == isn't
really useful in Java since Java requires that the expression in an if
evaluate to a boolean value, so unless the constant is a boolean,
you'd get a compilation error either way you put the arguments. (and
if it is a boolean, you shouldn't be using == anyway...)
There is no difference, and
if (foo == null)
enter code here
is the prefered way; however in C, you would put constants to the left since there would be an error if you used = instead of ==

(a != null) or (null != a)

Is there any difference in comparing a variable with null or comparing the null with a variable?
For example, which comparation is better (a != null) or (null != a) ?
I've read somewhere that the second one is faster but didn't find the reason for this.
No, none is faster. That's a plain lie. There is no advantage of using the second version. Only making readability worse.
This all came from C, where you could erroneously write
if(x = 3)
instead of
if( x == 3)
Some people thought that it'd be best to write the constant first, in which case if you wrote =instead of ==, you'd get a compiler error. So some sources recommended writing
if(3 == x)
Some people didn't know why this was necessary and carried on and generalized this idea to constructs and languages where it makes absolutely no sense. IMO it didn't make a lot of sense in the original C context either, but that's a matter of personal taste.
Even if there were a difference in speed, I'd expect it to be entirely insignificant in 99.99% of apps. As it is, I wouldn't expect there to be any speed difference. Personally I find if (a != null) more readable - and readability is much more important than performance in most cases.
You might only want to use a literal before the variable when doing operations with strings.
if("abcd".equals(name)) doesn't throw a NPE where as if(name.equals("abcd")) does if at all name were to be null.
This is usually done to prevent accidental assignment instead of comparison:
( a = null ) //will not give error
( null = a ) //will give error
I'm fairly sure efficiency is not a reason, and if it were, an optimizer would render the code the same in binary.
No, there is no difference what so ever.
not really, not in java now anyways. in older days, may be C, you could accidentally forget the exclamation mark and the code would compile fine. basically, a = null would be taken as an expression that assigned null to a and always evaluate to true (because assignment was successful).
Today's compilers are far more robust. Although, old habits die hard and I still write null != a :-)

if(null!=variable) why not if(variable!=null)

Hi
In our company they follow a strict rule of comparing with null values. When I code
if(variable!=null) in code review I get comments on this to change it to if(null!=variable). Is there any performance hit for the above code?
If anybody explains highly appreciated.
Thanks in advance
I don't see any advantage in following this convention. In C, where boolean types don't exist, it's useful to write
if (5 == variable)
rather than
if (variable == 5)
because if you forget one of the eaqual sign, you end up with
if (variable = 5)
which assigns 5 to variable and always evaluate to true. But in Java, a boolean is a boolean. And with !=, there is no reason at all.
One good advice, though, is to write
if (CONSTANT.equals(myString))
rather than
if (myString.equals(CONSTANT))
because it helps avoiding NullPointerExceptions.
My advice would be to ask for a justification of the rule. If there's none, why follow it? It doesn't help readability.
No performance difference - the reason is that if you get used to writing (null == somevar) instead of (somevar == null), then you'll never accidentally use a single equals sign instead of two, because the compiler won't allow it, where it will allow (somevar = null). They're just extending this to != to keep it consistent.
I personally prefer (somevar == null) myself, but I see where they're coming from.
It's a "left-over" from old C-coding standards.
the expression if (var = null) would compile without problems. But it would actually assign the value null to the variable thus doing something completely different. This was the source for very annoying bugs in C programs.
In Java that expression does not compile and thus it's more a tradition than anything else. It doesn't erver any purpose (other than coding style preferences)
This has nothing to do with performance. It's used to prevent that you assign accidentally instead of comparing. An assignment null = var won't make any sense. But in Java var = null also won't compile so the rule of turning them around doesn't make sense anymore and only makes the code less readable.

Categories