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")));
Related
I was asked this question in interview. Which of the following is better to use
MyInput.equals("Something");
Or
"Something".equals(MyInput);
Thanks
I would go for
"Something".equals(MyInput);
in this case if MyInput is null then it won't throw NullPointerException
Here we are sure that the object on which equals() is going to invoke is NOT NULL.
And if you expect NullPointerException from your code to take some decision or throw/wrap it, then go for first.
There is no performance impact
To be the contrarian.... :)
The first line might crash if MyInput is null, but that is just a code-convenience programmers (usually with a C hangover) use when they don't want to assert that 'MyInput' can be null.
If the second option is used, then maybe this line won't cause a NullPointerException, but the following lines might.
I believe that it is better know the possible state of your variables rather than rely on some code-construct that eases your conscience.
Well how about we write our whole code upside down for a change?
Those who like their constants first, how would they feel when they see this?
if ( 2 == i)
Hiding a NullPointerException, in my opinion, is never a benefit but a shortcoming in the design.
If you never expect a NullPointerException but got one, then you need to let your application blow, follow the logs and see why this happened. It could be a business case that you missed altogether :)
If you optionally expect a null parameter and are not interested in handling it separately, then use a utility method like StringUtils.equals(...)
That said, I never allow any of my team members to use the second form because it is not consistent and not readable.
The former will raise a NullPointerException if MyInput is null, while the latter will just return false, so the latter may be preferable in certain cases (or possibly the former, if you don't expect MyInput to be null and want to fail fast).
If you want to be a real smarty-pants you could point out the possibility that MyInput could be a special subclass of String that has over-ridden the equals and hashcode methods. In that case the ordering of the statement is vitally important.
Here's a real-life example - how about if you want to compare Strings that have numbers in them and you want leading zeroes ignored? For example, Lecture1 would equal Lecture01.
i would go to "something".equals(myInput); because variable can be null simply it throw a exception if variable is null .
A good developer will always try to avoid a NullPointerException, hence the best answer would be to use "Something".equals(myInput).
I heard several times that in using boolean equals(Object o) to compare Strings, it's better to put the constant on the left side of the function as in the following:
Bad: myString.equals("aString");
Good: "aString".equals(myString);
Why is this?
Because if myString is null you get an exception. You know "aString" will never be null, so you can avoid that problem.
Often you'll see libraries that use nullSafeEquals(myString,"aString"); everywhere to avoid exactly that (since most times you compare objects, they aren't generated by the compiler!)
This is a defensive technique to protect against NullPointerExceptions. If your constant is always on the left, no chance you will get a NPE on that equals call.
This is poor design, because you are hiding NullPointerExceptions. Instead of being alerted that string is null, you will instead get some weird program behaviour and an exception being thrown somewhere else.
But that all depends if 'null' is a valid state for your string. In general 'null's should never be considered a reasonable object state for passing around.
I was asked this question in interview. Which of the following is better to use
MyInput.equals("Something");
Or
"Something".equals(MyInput);
Thanks
I would go for
"Something".equals(MyInput);
in this case if MyInput is null then it won't throw NullPointerException
Here we are sure that the object on which equals() is going to invoke is NOT NULL.
And if you expect NullPointerException from your code to take some decision or throw/wrap it, then go for first.
There is no performance impact
To be the contrarian.... :)
The first line might crash if MyInput is null, but that is just a code-convenience programmers (usually with a C hangover) use when they don't want to assert that 'MyInput' can be null.
If the second option is used, then maybe this line won't cause a NullPointerException, but the following lines might.
I believe that it is better know the possible state of your variables rather than rely on some code-construct that eases your conscience.
Well how about we write our whole code upside down for a change?
Those who like their constants first, how would they feel when they see this?
if ( 2 == i)
Hiding a NullPointerException, in my opinion, is never a benefit but a shortcoming in the design.
If you never expect a NullPointerException but got one, then you need to let your application blow, follow the logs and see why this happened. It could be a business case that you missed altogether :)
If you optionally expect a null parameter and are not interested in handling it separately, then use a utility method like StringUtils.equals(...)
That said, I never allow any of my team members to use the second form because it is not consistent and not readable.
The former will raise a NullPointerException if MyInput is null, while the latter will just return false, so the latter may be preferable in certain cases (or possibly the former, if you don't expect MyInput to be null and want to fail fast).
If you want to be a real smarty-pants you could point out the possibility that MyInput could be a special subclass of String that has over-ridden the equals and hashcode methods. In that case the ordering of the statement is vitally important.
Here's a real-life example - how about if you want to compare Strings that have numbers in them and you want leading zeroes ignored? For example, Lecture1 would equal Lecture01.
i would go to "something".equals(myInput); because variable can be null simply it throw a exception if variable is null .
A good developer will always try to avoid a NullPointerException, hence the best answer would be to use "Something".equals(myInput).
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).
I'm wondering if it is an accepted practice or not to avoid multiple calls on the same line with respect to possible NPEs, and if so in what circumstances. For example:
anObj.doThatWith(myObj.getThis());
vs
Object o = myObj.getThis();
anObj.doThatWith(o);
The latter is more verbose, but if there is an NPE, you immediately know what is null. However, it also requires creating a name for the variable and more import statements.
So my questions around this are:
Is this problem something worth
designing around? Is it better to go
for the first or second possibility?
Is the creation of a variable name something that would have an effect performance-wise?
Is there a proposal to change the exception
message to be able to determine what
object is null in future versions of
Java ?
Is this problem something worth designing around? Is it better to go for the first or second possibility?
IMO, no. Go for the version of the code that is most readable.
If you get an NPE that you cannot diagnose then modify the code as required. Alternatively, run it using the debugger and use breakpoints and single stepping to find out where the null pointer is coming from.
Is the creation of a variable name something that would have an effect performance-wise?
Adding an extra variable may increase the stack frame size, or may extend the time that some objects remain reachable. But both effects are unlikely to be significant.
Is there a proposal to change the exception message to be able to determine what object is null in future versions of Java ?
Not that I am aware of. Implementing such a feature would probably have significant performance downsides.
The Law of Demeter explicitly says not to do this at all.
If you are sure that getThis() cannot return a null value, the first variant is ok. You can use contract annotations in your code to check such conditions. For instance Parasoft JTest uses an annotation like #post $result != null and flags all methods without the annotation that use the return value without checking.
If the method can return null your code should always use the second variant, and check the return value. Only you can decide what to do if the return value is null, it might be ok, or you might want to log an error:
Object o = getThis();
if (null == o) {
log.error("mymethod: Could not retrieve this");
} else {
o.doThat();
}
Personally I dislike the one-liner code "design pattern", so I side by all those who say to keep your code readable. Although I saw much worse lines of code in existing projects similar to this:
someMap.put(
someObject.getSomeThing().getSomeOtherThing().getKey(),
someObject.getSomeThing().getSomeOtherThing())
I think that no one would argue that this is not the way to write maintainable code.
As for using annotations - unfortunately not all developers use the same IDE and Eclipse users would not benefit from the #Nullable and #NotNull annotations. And without the IDE integration these do not have much benefit (apart from some extra documentation). However I do recommend the assert ability. While it only helps during run-time, it does help to find most NPE causes and has no performance effect, and makes the assumptions your code makes clearer.
If it were me I would change the code to your latter version but I would also add logging (maybe print) statements with a framework like log4j so if something did go wrong I could check the log files to see what was null.