why use null != anything instead of anything!=null? [duplicate] - java

This question already has answers here:
object==null or null==object?
(11 answers)
Closed 7 years ago.
I have seen various codes of my seniors and they have used this at many places.What effect does it have? why cant they include anything != null. This is true for below thing too
"true".equals(x).
Why is this so?

anything != null is exactly equivalent to null != anything.
On the other hand, "true".equals(x) avoids the need to check if x is null when doing x.equals("true").

The reason for including constants on the left hand side of an equals expression is to avoid NullPointerException even when the variable is null. This also improves the readability of the expression.
That being said, null!=something is a personal choice and I would prefer using something!=null.

These are two separate practices.
Using null on the left side when comparing to null ensures that you won't, by mistake, use = instead of ==. However, this is a practice taken from languages other than Java, as in Java the expression
if ( something = null )
is going to fail as it does not resolve to a boolean value. In other languages it may be permissible to use a condition whose value is actually a pointer.
Thus this practice has no meaning in Java.
The second practice, as you were told, has to do with preventing a NullPointerException. It should be noted that this practice is controversial, because it allows a null to propagate to a later point in the program, and that usually means that it will be harder to find when it causes a bug.

This is called a Yoda condition. Among other things, it helps prevent an accidental assignment due to a missing = or !, as in foo = null. The reverse, null = foo, would not even compile.
That said, it is purely a stylistic preference. foo != null is logically equivalent to null != foo.

That check is so the program ensures the variable in question has been initialized before reading it. If a program tries to access a null variable, it will crash (specifically in Java it will throw a NullPointerException). It is a critical aspect of defensive programming.
As far as ordering, the evaluation of whether something is null or not is commutative. Meaning:
something != null
Is the same as
null != something
It is all a matter of personal preference. And as #manouti explains above, "true".equals(x) avoids the need to check if x is null when doing x.equals("true"), so you save a line of code.

Seems that some people prefer null != anything, because anything might be quite long expression, so writing null first makes it visible in the narrow window and simplifies code reading ("ok, we just check if something is not null"). But it's totally a matter of style.
As for "true".equals(x), it's well explained by #manouti.

Related

Null check coding standard [duplicate]

This question already has answers here:
Which has better performance: test != null or null != test [duplicate]
(8 answers)
Closed 9 years ago.
I have a doubt regarding coding standard of a null check.
I want to know the difference between
if(a!=null)
and
if(null!=a)
which one is better,which one to use and why?
Both are same in Java, as only boolean expressions can be inside an if. This is just a coding style preference by programmer and most of them use null != a.
The null != a is an old practice in programming languages like Java,C++ (called as Yoda Conditions).
As it is valid to write if (a = null) and accidentally assign null to the a so writing null first is a guard to stop this accident from happening.
There is no difference. But the first is more common. The second is also called "Yoda Conditions" because of its unnatural "grammar".
Once I was working in a project where the coding guideline was to use if (null != a) because they thought it is easier for the developer to understand that the constant value has to come first always (as in CONSTANT_VALUE.equals(variable). That was pretty annoying to me.
They're both the same. It depends on your coding style.
From the compiler's point of view, they're exactly the same. But the first form is more readable, so I'd advise you to use that one.
No difference betwwen them if statement works based on result of expression
so u write either if(a!=null) or if(null!=a) will produce true or false then result is evaluated.
So it doesnt matter you write which you like
They both are same. Although the first variant is common the second variant is useful if you know the first variable is not null
Example "some value".equals(your_variable) , some value can be any value you know is not null. This will avoid NPE when your_variable is null.
String str = "somevalue";
if(str != null && str.equals("somevalue")) { }
if("somevalue".equals(str)) { }
Both the conditions will be same if str is null or not.

Which has better performance: test != null or null != test [duplicate]

This question already has answers here:
object==null or null==object?
(11 answers)
Closed 2 years ago.
Consider the following two lines of code
if (test ! = null)
and
if (null != test)
Is there is any difference in above two statements, performance wise? I have seen many people using the later and when questioned they say its a best practice with no solid reason.
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.
So I personally prefer first one because of readability, people tend to read from left to right, which read as if test is not equal to null instead of null is not equal to test.
They are exactly the same. The second one can make sense when using equals:
if("bla".equals(test))
can never throw a NullPointerException whereas:
if(test.equals("bla"))
can.
There is no performance difference but I personally find the second one being confusing.
Second one looks for me like "Yoda condition", i.e. if(2 == x) ... and is much less readable.
It's best practice to avoid some basic typo's that most modern IDE's will pick up, because sometimes you want to do comparisons between more complex types that are not null and end up doing accidental assignments. So the pattern remains the same, but I've never seen this linked to performance and have never seen it generate special byte code.
The idea is to have the static, known value first, so you can't throw any kind of weird exception when you perform the comparison.
Neither of the two methods are "more correct" though, so it's entirely up to you to decide what you wish to use.
there is no difference. But in second way you avoid the typo like test = null. Beacause in second way you'll get compiler error.
It's not a best practice to use the latter one. Both are equivalent, but the former is easier to read.
This "best practice" comes from C where boolean don't exist. Integers are used instead, and if (foo = 1) is not a syntax error, but is completely different from if (foo == 1).
In Java, only boolean expressions can be inside an if, and this practice doesn't make much sense.
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.

Object null-ness check in Java

Which one is recommended and to be used to check the Object null-ness?
null != Object
or
Object != null
and other way
null == Object
or
Object == null
...and is there any difference between them?
(In)equality is commutative, so there is no difference.
Historically the former stems from C to avoid accidentally assigning a value in a conditional statement, however that mostly applies to ==, not !=. Also Java requires the condition in a conditional statement to have a boolean value, so the only place where it could go wrong nowadays would be
if (a == false) ...
if you accidentally omit one of the =. A rare case, I guess (though probably not so much, given what students frequently write in their first two terms). Joonas also points out another (more obscure) case in the comments.
It's always more readable to use
Object != null
because that reads as "the object is not null", which is literally what the condition is.
The only case where you want to swap the two is to avoid accidentally using
Object = null
which will return true even though it is not the desired behavior, when you wanted to say
Object == null
but in reality not only do modern tools catch these kinds of mistakes, but wide use of the reverse can actually be an impediment to anyone who has to read the code.

String equality in Java

I have seen both of these when checking the equality of two Java String's:
// Method A
String string1;
// ...
if("MyString".equals(string1)) {
// ...
}
and
// Method B
String string1;
// ...
if(string1.equals("MyString")) {
// ...
}
My question is: which one is better and more widely used?
If you are sure that string1 can never be null then option 2 is readable and preferred. Otherwise option 1. Intention of option 1 is to avoid potential null pointer.
Method A won't throw a null pointer exception. There is no better of the two. It depends on whether on not you want it to throw a npe (and you might want that in your overall design).
Method B will fail with NullPointerException on null string1, whereas Method A will never throw this. Some authorities mandate this "defensive" programming. They have influenced me to do it, though it still does not come naturally!
It's also possible to write
if (string1 != null && string1.equals("MyString")) ...
though tools such as FindBugs flags this as a possible error, assuming that you should have made sure that string1 was already non-null. (Can you rely on the order of evaluation?).
So there are different schools of thought.
Method a does not throw NullPointerException and hence very convenient. It is widely used also.
Exceptions are for exceptional processing and have more overhead than checking for error conditions and handling them with regular logic. If you have been programming for a decade a NPE is a cringe matter which usually indicates careless code. Avoid them by using "constant".equals(variable) and people who read your code and use it will be happier.
The second one is more widely used. Neither is better.
It's the same idea as
if (1 == x)
but without a specific reason. but for a different reason. (Null pointer as noted by others).

Java : "xx".equals(variable) better than variable.equals("xx") , TRUE?

I'm reviewing a manual of best practices and recommendation coding java I think is doubtful.
Recomendation:
String variable;
"xx".equals(variable) // OK
variable.equals("xx") //Not recomended
Because prevents appearance of NullPointerException that are not controlled
Is this true?
This is a very common technique that causes the test to return false if the variable is null instead of throwing a NullPointerException. But I guess I'll be different and say that I wouldn't regard this as a recommendation that you always should follow.
I definitely think it is something that all Java programmers should be aware of as it is a common idiom.
It's also a useful technique to make code more concise (you can handle the null and not null case at the same time).
But:
It makes your code harder to read: "If blue is the sky..."
If you have just checked that your argument is not null on the previous line then it is unnecessary.
If you forgot to test for null and someone does come with a null argument that you weren't expecting it then a NullPointerException is not necessarily the worst possible outcome. Pretending everything is OK and carrying until it eventually fails later is not really a better alternative. Failing fast is good.
Personally I don't think usage of this technique should be required in all cases. I think it should be left to the programmer's judgement on a case-by-case basis. The important thing is to make sure you've handled the null case in an appropriate manner and how you do that depends on the situation. Checking correct handling of null values could be part of the testing / code review guidelines.
It is true. If variable is null in your example,
variable.equals("xx");
will throw a NPE because you can't call a method (equals) on a null object. But
"xx".equals(variable);
will just return false without error.
Actually, I think that the original recommendation is true. If you use variable.equals("xx"), then you will get a NullPointerException if variable is null. Putting the constant string on the left hand side avoids this possibility.
It's up to you whether this defense is worth the pain of what many people consider an unnatural idiom.
This is a common technique used in Java (and C#) programs. The first form avoids the null pointer exception because the .equals() method is called on the constant string "xx", which is never null. A non-null string compared to a null is false.
If you know that variable will never be null (and your program is incorrect in some other way if it is ever null), then using variable.equals("xx") is fine.
It's true that using any propertie of an object that way helps you to avoid the NPE.
But that's why we have Exceptions, to handle those kind of thing.
Maybe if you use "xx".equals(variable) you would never know if the value of variable is null or just isn't equal to "xx". IMO it's best to know that you are getting a null value in your variable, so you can reasign it, rather than just ignore it.
You are correct about the order of the check--if the variable is null, calling .equals on the string constant will prevent an NPE--but I'm not sure I consider this a good idea; Personally I call it "slop".
Slop is when you don't detect an abnormal condition but in fact create habits to personally avoid it's detection. Passing around a null as a string for an extended period of time will eventually lead to errors that may be obscure and hard to find.
Coding for slop is the opposite of "Fail fast fail hard".
Using a null as a string can occasionally make a great "Special" value, but the fact that you are trying to compare it to something indicates that your understanding of the system is incomplete (at best)--the sooner you find this fact out, the better.
On the other hand, making all variables final by default, using Generics and minimizing visibility of all objects/methods are habits that reduce slop.
If you need to check for null, I find this better readable than
if (variable != null && variable.equals("xx")). It's more a matter of personal preference.
As a side note, here is a design pattern where this code recommendation might not make any difference, since the String (i.e. Optional<String>) is never null because of the .isPresent() call from the design pattern:
Optional<String> gender = Optional.of("MALE");
if (gender.isPresent()) {
System.out.println("Value available.");
} else {
System.out.println("Value not available.");
}
gender.ifPresent(g -> System.out.println("Consumer: equals: " + g.equals("whatever")));

Categories

Resources