In Java, objects are, by default, initialized to null
.
I recently came across this answer while doing research into handling NPE properly: https://softwareengineering.stackexchange.com/a/187225
The following is my primary take-away from the post:
If you never set a variable to null you can never have an unexpected null.
Don't allow null parameters
I've been wondering how to handle this in Java and Android. Many of the crash reports I see on the developer dashboard are NPE, and I've noticed that in my code, I use null
checking to see if I can continue with an operation.
I'm combing through my codebase trying to remove null
and default instantiation as much as possible, but I'm running into a few areas where this appears impossible and I'm not sure how to fix the errors which arise from these variables.
For example, when using the Google Maps API, you must declare a GoogleMap
object. The way I currently have it set up is to declare the variable as a member of my Activity
, then initialize it during onCreate()
. Unfortunately, during onResume()
when I call .clear()
on the GoogleMap
, occasionally the field will be null
. I'm unable to reproduce this error in my own environment, which led me to do more reading into handling NPE.
In another (very popular) question here: Avoiding != null statements, The top and accepted answer recommends three strategies for resolving this issue.
- The
assert
statement. On the surface, this looks more like unit-testing/debug code, especially since Java ignoresassert
by default. - The Null Object pattern. This is probably the most appealing of the solutions presented as it ends up looking and feeling cleaner. However, when working with external libraries, I'm not sure that this is an option. Extending an external library seems messy.
- The try/catch. This is just difficult. Since
null
is so pervasive in Java, the code will end up densely peppered with try/catch for everything that could be null, or end up having swaths of code blocked off, which catching errors in won't allow much precision in handling the aftermath.
My question is, is there another option? Perhaps a coding paradigm I can use or some kind of built-in that might fix this?
Optimally, I would like a solution where I don't crash, lose data reliability, or lose application functionality.
Note - This is not a question about problems with my code, this is a question about how to defensively write code to prevent unexpected NPE in a language where the default initialization is null
.