Despite being a Java 8 only project, Caffeine returns null from a number of methods in its public API. For example, cache.get returns null to represent that no element exists in the cache.
It would be nice if instead an Optional<T> was returned where Optional.empty() represents that no element is in the cache, so that type safety is preserved. null can still be used internally, Optional only needs to be exposed to users of the library.
Here are some of the reasons we didn't go down that route.
weak and soft values won't behave as desired.Optional is the most convenient version of this. Unfortunately Java doesn't provide a flatten method for double optionals.Optional.get. We tend to recommend users compute through the cache rather than check for presence, where a null indicates non-computable (e.g. record not found in the database).null via checked exceptions so that null hostile API was chosen. But Map.computeIfAbsent didn't follow that idiom, lambdas are not exception friendly, and his advice was more applicable for the Java 4 style code of the day.null can still be used internally, Optional only needs to be exposed to users.I think Optional in Java doesn't fit as cleanly as any of us would like, and many developers would feel it forced upon them undesirably. If you prefer an Optional-based API then I think writing an adapter API is a better route for the time being.
Most helpful comment
Here are some of the reasons we didn't go down that route.
weakandsoftvalues won't behave as desired.Optionalis the most convenient version of this. Unfortunately Java doesn't provide aflattenmethod for double optionals.Optional.get. We tend to recommend users compute through the cache rather than check for presence, where anullindicates non-computable (e.g. record not found in the database).nullvia checked exceptions so that null hostile API was chosen. ButMap.computeIfAbsentdidn't follow that idiom, lambdas are not exception friendly, and his advice was more applicable for the Java 4 style code of the day.nullcan still be used internally, Optional only needs to be exposed to users.I think Optional in Java doesn't fit as cleanly as any of us would like, and many developers would feel it forced upon them undesirably. If you prefer an Optional-based API then I think writing an adapter API is a better route for the time being.