Skip to content

Instantly share code, notes, and snippets.

@SwingGuy1024
Last active December 15, 2018 03:31
Show Gist options
  • Save SwingGuy1024/3374e0a1b79ee2616066e056569e0a52 to your computer and use it in GitHub Desktop.
Save SwingGuy1024/3374e0a1b79ee2616066e056569e0a52 to your computer and use it in GitHub Desktop.
Brian Goetz Blog Post

Taken from http://mail.openjdk.java.net/pipermail/lambda-dev/2012-September/005952.html

java.util.Optional fields

Brian Goetz brian.goetz at oracle.com

Fri Sep 21 07:51:18 PDT 2012

An alternative of throwing NoSuchElementException was replaced by returning an Optional.

Having Optional enables me to do fluent API thingies like: stream.getFirst().orElseThrow(() -> new MyFancyException())

I would speculate this was the intended goal for Optional.

Absolutely.

Take the example from SotL/L from the reflection library.

Old way:

for (Method m : enclosingInfo.getEnclosingClass().getDeclaredMethods()) {
      if (m.getName().equals(enclosingInfo.getName()) ) {
          Class<?>[] candidateParamClasses = m.getParameterTypes();
          if (candidateParamClasses.length == parameterClasses.length) {
              boolean matches = true;
              for(int i = 0; i < candidateParamClasses.length; i++) {
                  if (!candidateParamClasses[i].equals(parameterClasses[i])) {
                      matches = false;
                      break;
                  }
              }

              if (matches) { // finally, check return type
                  if (m.getReturnType().equals(returnType) )
                      return m;
              }
          }
      }
  }
  throw new InternalError("Enclosing method not found");

Without Optional:

Method matching =
      Arrays.asList(enclosingInfo.getEnclosingClass().getDeclaredMethods())
         .filter(m -> Objects.equals(m.getName(), enclosingInfo.getName())
         .filter(m ->  Arrays.equals(m.getParameterTypes(), parameterClasses))
         .filter(m -> Objects.equals(m.getReturnType(), returnType))
         .getFirst();
if (matching == null)
     throw new InternalError("Enclosing method not found");
return matching;

This is much better, but we still have a "garbage varaiable", matching, which we have to test and throw before returning.

With Optional:

return
   Arrays.asList(enclosingInfo.getEnclosingClass().getDeclaredMethods())
         .filter(m -> Objects.equals(m.getName(), enclosingInfo.getName())
         .filter(m ->  Arrays.equals(m.getParameterTypes(), parameterClasses))
         .filter(m -> Objects.equals(m.getReturnType(), returnType))
         .findFirst()
         .getOrThrow(() -> new InternalError(...));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment