Before calling a function of an object, I need to check if the object is null, to avoid throwing a NullPointerException
.
What is the best way to go abou
You also can use StringUtils.isNoneEmpty("")
for check is null or empty.
In Java 8, the best way to check for null is:
Objects.isNull(obj) //returns true if the object is null
Objects.nonNull(obj) //returns true if object is not-null
if(Objects.nonNull(foo) && foo.something()) // Uses short-circuit as well. No Null-pointer Exceptions are thrown.
Apart from this... You can also go with Guava's Optional Class
Method 4 is best.
if(foo != null && foo.bar()) {
someStuff();
}
will use short-circuit evaluation, meaning it ends if the first condition of a logical AND
is false.
In Java 7, you can use Objects.requireNonNull()
.
Add an import of Objects
class from java.util
.
public class FooClass {
//...
public void acceptFoo(Foo obj) {
//If obj is null, NPE is thrown
Objects.requireNonNull(obj).bar(); //or better requireNonNull(obj, "obj is null");
}
//...
}
if you do not have an access to the commons apache library, the following probably will work ok
if(null != foo && foo.bar()) {
//do something
}
Method 4 is far and away the best as it clearly indicates what will happen and uses the minimum of code.
Method 3 is just wrong on every level. You know the item may be null so it's not an exceptional situation it's something you should check for.
Method 2 is just making it more complicated than it needs to be.
Method 1 is just method 4 with an extra line of code.