News for hackers. Stuff that matters.
Re:Modern Java – A Guide to Java 8 by norswap on Monday November 16, 2015 @09:35PM (#10578837)
Two things. First, why is it better than:

    String foo;
    
    if (parameter != null) {
        foo = ... ;
    }
    else {
        foo = defaultValue;
    }
or even this, if you express all your transformations as a single expression:

    String foo = parameter != null
        ? ...
        : defaultValue
I don't get it. Your way of doing seem awfully more verbose. Please note that I'm not against Optional in general (although they are overplayed in my opinion).

Second thing, I can't shake off the feeling of inefficiency: building these closures up, calling them. Lots of indirection for something that's probably very simple. I wouldn't want to call this code in a hot loop. But then maybe it's not in a hot loop. Before you bring that up, the sufficiently smart (JIT) compiler doesn't exist. "Sometimes suprisingly dumb" is a better qualifier for many compilers.

Note that I work with Java, and use the Java 8 features a lot. I just think this isn't a really good example.

Re:Modern Java – A Guide to Java 8 by incepted on Tuesday November 17, 2015 @12:03AM (#10579261)
Actually, your way is awfully more verbose, but you didn't notice it because you ellipsized the verbosity.

If you actually take the time to translate OP's code with your own, you will soon find yourself indented six levels with "if (a != null) { ... if (b != null) { ... if (c != null) {...

You get the idea.

Monads (the type class that Optional belongs to) flatten all this boiler plate with a function called... flatMap! And you don't even need to know about it, all you need to do is chain the calls like OP did:

    Optional.ofNullable(paramater)
                       .filter(...)
                       .map(a -> ...)
                       .map(b -> ...)
                       .orElseGet(() -> ...)
                       .orElse(defaultValue)
without having to check against null every step along the way.
Re:Modern Java – A Guide to Java 8 by norswap on Tuesday November 17, 2015 @05:42PM (#10584548)
Point taken. I'll tentatively argue if all your functions can return null you have other problems to contend with, but what you said makes sense.