• Suppose you have a simple date string: "2015-02-27"

    Regular expressions allow to parse the date and extract parts thereof: (dddd)-(dd)-(dd) defines a pattern which matches the digits and defines capturing […]

  • Tony Hoare, inventor of the null reference, apologetically called it “the billion dollar mistake”.

    The problem with null is not that it was invented back in 1965, but that we are still struggling with it 50 yea […]

    • I’m not sure that:

      String value = result.map(String::trim).orElse(“”);

      is any better than:

      String value = (result!=null) ? result.trim() : “”;

      Using the ternary makes it obvious that this is a simple check to deal with null. I find the ‘map’ method quite distracting from what the line of code is actually doing (providing a default in the event of a null).

      • I prefer the:

        result.orElseGet(() -> “”).trim();

        syntax as to my eyes it makes more logical sense, but in a codebase that follows a strict use of Optional, as the article states, you as the API designed are making it clear that “this method call can return a value, or not”. In the places that Optional is not present you are effectively saying “this is guaranteed to never return null” and hence null checks can be skipped. This is a lot more obvious in Scala where everybody just seems conditioned to using Optional.

    • The difference between a method returning null for elements that aren’t found, or Optional.empty() for the same, is that you just can’t forget the check. You will need it if you want your code to even compile, as stated in “Types to the rescue” in TFA.

      Some other example…

      Optional ownerOptional = find(“Roger”);
      Person owner = ownerOptional.orElse(defaultOwner);

      With a null check, it’s easy to have a NPE (thus at runtime) rather than a safer compile-time check:

      Person owner = find(“Roger”); // easy to forget to check for null…

      It’s even more obvious if you use multiple map() operations, ifPresent(() -> {…}) etc.

      The “basic behaviour” just can lead to errors that are easy to check at compile time with Optional.

      Is it more verbose? In dumb examples, yes. In real code, you start writing thing differently, and it becomes more succinct over time in my experience. Things like building complex CriteriaBuilder requests with many optional (!) parts come into my mind. Combining map() and ifPresent() can help you build them easily, and still maintain in in a readable way.

  • Nice post! I disagree with “Tip #6: Don’t use optional!” though. Here’s my take on it: http://netzwerg.ch/blog/2015/02/11/java-8-optional/