RFR 8071670: java.util.Optional: please add a way to specify if-else behavior

Louis Wasserman lowasser at google.com
Thu Feb 12 19:29:57 UTC 2015


I'm not sure I can share hard numbers, but the ratio of

if (optional.isPresent()) {
  // non-returning statements here
}

to

if (optional.isPresent()) { // or negated
  // non-returning statements here
} else {
  // non-returning statements here
}

is ~5.5x in favor of the no-else case.  Both patterns have large numbers of
hits, though, so I'm satisfied that this is not an unreasonable thing to do.

I can possibly try to extract statistics on how many of these cases would
be easily converted to method references and other things that might be
easier to express with functional interfaces, but I'm not sure how
necessary that actually is.


On Thu Feb 12 2015 at 10:40:23 AM Daniel Fuchs <daniel.fuchs at oracle.com>
wrote:

> The new version looks good Paul!
>
> -- daniel
>
> On 2/12/15 6:50 PM, Paul Sandoz wrote:
> > On Feb 12, 2015, at 3:50 PM, Daniel Fuchs <daniel.fuchs at oracle.com>
> wrote:
> >
> >> Hi Paul,
> >>
> >> This looks good - I have noticed one copy/paste error in the javadoc
> >> though:
> >>
> >> OptionalInt.java:
> >>
> >> looks like the throws clause of ifPresent and ifPresentOrElse have been
> >> interverted:
> >>
> >> 138      * @throws NullPointerException if a value is present and
> {@code action} is
> >> 139      * null, or a value is not present and {@code emptyAction} is
> null.
> >> 140      */
> >> 141     public void ifPresent(IntConsumer action) {
> >> 142         if (isPresent) {
> >> 143             action.accept(value);
> >> 144         }
> >> 145     }
> >> 146
> >> 147     /**
> >> 148      * If a value is present, perform the given action with the
> value,
> >> 149      * otherwise perform the given empty-based action.
> >> 150      *
> >> 151      * @param action the action to be performed if a value is
> present
> >> 152      * @param emptyAction the empty-based action to be performed if
> a value is
> >> 153      * not present
> >> 154      * @throws NullPointerException if value is present and {@code
> action} is
> >> 155      * null
> >> 156      * @since 1.9
> >> 157      */
> >> 158     public void ifPresentOrElse(IntConsumer action, Runnable
> emptyAction) {
> >>
> > Oops. Fixed.
> >
> >
> >> Concerning the test, should there be a test that verifies that NPE
> >> is thrown when null is passed - as specified in the javadoc?
> >>
> > Done.
> >
> > http://cr.openjdk.java.net/~psandoz/jdk9/JDK-8071670-Optiona
> l-ifPresentOrElse/webrev/
> >
> > Thanks,
> > Paul.
>
>



More information about the core-libs-dev mailing list