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
Method 4 is my preferred method. The short circuit of the && operator makes the code the most readable. Method 3, Catching NullPointerException, is frowned upon most of the time when a simple null check would suffice.
Simple one line Code to check for null :
namVar == null ? codTdoForNul() : codTdoForFul();
If you control the API being called, consider using Guava's Optional class
More info here. Change your method to return an Optional<Boolean>
instead of a Boolean
.
This informs the calling code that it must account for the possibility of null, by calling one of the handy methods in Optional
Your last proposal is the best.
if (foo != null && foo.bar()) {
etc...
}
Because: