I use object != null
a lot to avoid NullPointerException.
Is there a good alternative to this?
For example I often use:
Doing this in your own code and you can avoid != null checks.
Most of the time null checks seem to guard loops over collections or arrays, so just initialise them empty, you won't need any null checks.
// Bad
ArrayList lemmings;
String[] names;
void checkLemmings() {
if (lemmings != null) for(lemming: lemmings) {
// do something
}
}
// Good
ArrayList lemmings = new ArrayList();
String[] names = {};
void checkLemmings() {
for(lemming: lemmings) {
// do something
}
}
There is a tiny overhead in this, but it's worth it for cleaner code and less NullPointerExceptions.