Eliminating Null Pointer Exceptions
How to avoid null pointer exception in java - Stack Overflow
JUnit - Test fails (null pointer exception) for no apparent reason
Solution to NullPointerException in java?
Videos
So, this is more of a thought experiment and something I've been wondering for a while. IMO, the existence of null pointers in a memory safe language is contrary to its purpose. What if all uninitialized objects had a default value of empty instead of null? There would be no memory allocation until it was explicitly defined. All interactions with the uninitialized object would behave as if the object were empty and did not fire Null Pointer Exceptions.
Attack!
Other than catching the error, if you are going to work with something which might be null, you might want to throw in null checks.
What you could do to reduce the chances of having to make null checks, would be to never return null from your methods, unless it is really necessary, for instance:
public IList<String> getUserNames()
{
//No usernames found...
return new ArrayList<String>();
//As opposed to returning null
return null;
}
By returning the empty list, a call to the above code would result into something like so: for(String name : this.getUserNames()) {...}. If no user names where found, the loop will not execute.
If on the other hand, you return null, you would need to do something like so:
List<String> userNames = this.getUsernames();
if(userNames != null)
for(String userName : userNames) {....}
Could you elaborate on what you mean be avoiding NPEs? It can be done in many ways. In your case you shouldn't be passing null into your String.
A general rule that has been taught to me by fellow SO users is to always catch NPEs as early as possible (to avoid collateral damage throughout your application).
For parameter validation you'll most probably need to use Objects#requireNonNull.
You may also declare a simple if-statement depending on the scenario, like so - if (name != null)
You also must realise that in some cases null may be required and thus handling such an NPE would be different. If you are not going to actually do something with the Exception, it should not be caught as it's possibly harmful to catch an exception and then simply discard it.
The following discusses when you ought to throw an exception or not - When to throw an exception?
Upon further investigation, it seems that Java 1.8 also offers a new Optional class ( java.util.Optional ) which seems very useful and cleaner. Take a look at this Oracle document.