There are multiple legitimate uses of null
; although there are equally many (if not more) illegitimate ones.
As a couple which spring to mind:
Optional dependencies. In the below class; if a non-null
Notifier
is provided at construction; then this is used to be notified when things happen. But the class can still do it's doThing
method if there was no such Notifier
available (or required).
class ThingDoer {
private final Notifier notifier;
ThingDoer(final Notifier notifier) {
this.notifier = notifier;
}
void doThing() {
// Doing some stuff.
if (this.notifier != null) {
this.notifier.notify("Did thing");
}
}
}
Caching is another case (use the cached value if it's already been calculated, otherwise go find it from scratch - thread safety not considered here...). The same concept applies to lazily-loaded things; where you can keep the value as null
until it's first requested, and then keep it available to avoid recomputation on subsequent requests for it.
class CachedLookup {
private Result cachedResult = null;
Result getResult() {
if (this.cachedResult != null) {
return this.cachedResult;
}
this.cachedResult = this.getResultInternal();
return this.cachedResult;
}
private Result getResultInternal() {
// Whatever complex stuff here...
return new Result();
}
}