RFR(s): 8140281 add no-arg Optional.orElseThrow() as preferred alternative to get()

Stuart Marks stuart.marks at oracle.com
Thu Dec 21 00:53:56 UTC 2017

On 12/18/17 2:31 AM, Tagir Valeev wrote:
> I think that both methods could co-exist with slightly different
> semantics (even though they implementation is identical):
> ...
> Think of get() as
> an assertion-like method: if get() throws, then it's a bug in the code
> (most likely right in this method).
> ...
> If orElseThrow() throws, then
> it's an acceptable situation (e.g. we are inside the library method
> and it documents that NoSuchElementException could be thrown if some
> precondition is not met).

Right, so the semantic difference is between an assertion check and a 
precondition check. I agree that there is a difference, but get() doesn't really 
mean "assertion check" to me. The orElseThrow() method could be used for both, 
without much loss. I think it's because we experts are used to get(), and it's 
all we had for both cases in JDK 8 and 9, that there is discomfort with the 
prospect of reducing the status of get().

> However I don't like issuing a warning if
> get() is used like in the code above. And if get() will be deprecated,
> then we would need to issue warning on every get() usage. Thus I'm
> against the deprecation.

Yes, better warnings control would clearly be necessary before we would proceed 
with deprecation.

> I believe that for any kind of API you can find bad code which abuses
> it regardless on how many years passed since the API was released.
> That's not always the fault of API creators.

It's certainly possible to write bad code in any language, using any API, 
certainly right after it's been introduced. As time goes on, people learn more, 
articles are written and conference talks presented, etc., and good usage 
patterns tend to emerge.

The situation with get() seems qualitatively different. I consistently and 
repeatedly see it misused, and it doesn't seem to be getting any better. When 
this occurs, it indicates that there's something wrong with the API.


More information about the core-libs-dev mailing list