I'm trying to make a basic cache of a boolean value, and I did it like such:
private Boolean _valueCache = null;
private boolean getValue() {
try {
if (_valueCache == null) { // if cache was never filled
return _valueCache = getReader().getMyBooleanProperty(); // fill it and return the new value
}
return _valueCache; // else, return the cache
} catch (NullPointerException ex) { // getReader() returned null
return false; // that return may not be null in the future, so set nothing
}
}
Does this go against best practices? (letting a Boolean
have 3 values: true
, false
, and null
) I only want to cache this value, so I don't want to make an entire custom HashMap that mimics this behavior with a get-or-default method. That said, I've never done a cache this small so I don't know the downsides to it.
To clarify, I meant "ternary" as in "3-state", as opposed to "binary" as in "2-state". Sorry for any confusion.
myMethod(o)
branch to different method definitions at runtime (likemyMethod(Object o)
vsmyMethod(null o)
), or even to make a method take anull
. Also, the provided question's answer mentionsmethodA()->methodB()
, which will throw aNullPointerException
in Java ifmethodA()
returnsnull
.