Checked exceptions

Remi Forax forax at univ-mlv.fr
Thu Oct 17 19:19:08 UTC 2019


----- Mail original -----
> De: "Brian Goetz" <brian.goetz at oracle.com>
> À: "Thomas May" <tmay at clearwateranalytics.com>, "jdk-dev" <jdk-dev at openjdk.java.net>
> Envoyé: Jeudi 17 Octobre 2019 18:17:33
> Objet: Re: Checked exceptions

>> The example that comes to mind is Double#parseDouble.  It's annoying to have to
>> deal with NumberFormatException, the API would jive better if instead it
>> returned an Optional<Double>.  But I realize that isn't possible without a lot
>> of breakage, so what about instead a optionalParseDouble that returns a
>> Optional<Double>?
>>
> 
> Stepping back from the exceptions question for a minute, the way I would
> prefer to address problems like this is via pattern matching. If we
> expose a pattern whose target is a string, and which produces a binding
> variable of type double if the string is the string representation of a
> double, then either the pattern matches and produces a valid double, or
> it doesn't match.  The advantage of this over the Optional approach is
> that is nestable with other patterns, so if we have a pattern that
> produces a String, we can compose it (via nesting) with the
> double-parsing pattern.
> 
> Once we have pattern matching, it will make sense to expose all sorts of
> parsing patterns, which work similarly to the Optional-bearing version
> of your method, but compose better.

It should compose as well because it's the extractor pattern which powers the pattern matching in Scala [1]
(it's also called the railway switch pattern [2] by Scott Wlaschin).

  interface Matcher<T> {
    Optional<T> match(String text);

    default Matcher<T> or(Matcher<? extends T> matcher) {
      return text -> match(text).or(() -> matcher.match(text));
    }

    static Optional<Integer> parseDouble(String text) {
      return Optional.of(new Scanner(text)).filter(Scanner::hasNextDouble).map(Scanner::nextDouble);
    }
  }

  Matcher<Double> parseDouble = Matcher::parseDouble;
  Matcher<Double> fortyTwo = __ -> Optional.of(42.0);
  Matcher<Double> matcher = parseInt.or(fortyTwo);


Rémi

[1] http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.640.9064&rep=rep1&type=pdf
[2] https://fsharpforfunandprofit.com/rop/


More information about the jdk-dev mailing list