Why should Java 8's Optional not be used in arguments

前端 未结 20 1639
我寻月下人不归
我寻月下人不归 2020-11-22 11:33

I\'ve read on many Web sites Optional should be used as a return type only, and not used in method arguments. I\'m struggling to find a logical reason why. For example I h

相关标签:
20条回答
  • 2020-11-22 12:21

    This seems a bit silly to me, but the only reason I can think of is that object arguments in method parameters already are optional in a way - they can be null. Therefore forcing someone to take an existing object and wrap it in an optional is sort of pointless.

    That being said, chaining methods together that take/return optionals is a reasonable thing to do, e.g. Maybe monad.

    0 讨论(0)
  • 2020-11-22 12:21

    At first, I also preferred to pass Optionals as parameter, but if you switch from an API-Designer perspective to a API-User perspective, you see the disadvantages.

    For your example, where each parameter is optional, I would suggest to change the calculation method into an own class like follows:

    Optional<String> p1 = otherObject.getP1();
    Optional<BigInteger> p2 = otherObject.getP2();
    
    MyCalculator mc = new MyCalculator();
    p1.map(mc::setP1);
    p2.map(mc::setP2);
    int result = mc.calculate();
    
    0 讨论(0)
  • 2020-11-22 12:24

    Oh, those coding styles are to be taken with a bit of salt.

    1. (+) Passing an Optional result to another method, without any semantic analysis; leaving that to the method, is quite alright.
    2. (-) Using Optional parameters causing conditional logic inside the methods is literally contra-productive.
    3. (-) Needing to pack an argument in an Optional, is suboptimal for the compiler, and does an unnecessary wrapping.
    4. (-) In comparison to nullable parameters Optional is more costly.

    In general: Optional unifies two states, which have to be unraveled. Hence better suited for result than input, for the complexity of the data flow.

    0 讨论(0)
  • 2020-11-22 12:24

    The best post I've seen on the topic was written by Daniel Olszewski:

    Although it might be tempting to consider Optional for not mandatory method parameters, such a solution pale in comparison with other possible alternatives. To illustrate the problem, examine the following constructor declaration:

    public SystemMessage(String title, String content, Optional<Attachment> attachment) {
        // assigning field values
    }
    

    At first glance it may look as a right design decision. After all, we explicitly marked the attachment parameter as optional. However, as for calling the constructor, client code can become a little bit clumsy.

    SystemMessage withoutAttachment = new SystemMessage("title", "content", Optional.empty());
    Attachment attachment = new Attachment();
    SystemMessage withAttachment = new SystemMessage("title", "content", Optional.ofNullable(attachment));
    

    Instead of providing clarity, the factory methods of the Optional class only distract the reader. Note there’s only one optional parameter, but imagine having two or three. Uncle Bob definitely wouldn’t be proud of such code

    0 讨论(0)
  • 2020-11-22 12:29

    There are almost no good reasons for not using Optional as parameters. The arguments against this rely on arguments from authority (see Brian Goetz - his argument is we can't enforce non null optionals) or that the Optional arguments may be null (essentially the same argument). Of course, any reference in Java can be null, we need to encourage rules being enforced by the compiler, not programmers memory (which is problematic and does not scale).

    Functional programming languages encourage Optional parameters. One of the best ways of using this is to have multiple optional parameters and using liftM2 to use a function assuming the parameters are not empty and returning an optional (see http://www.functionaljava.org/javadoc/4.4/functionaljava/fj/data/Option.html#liftM2-fj.F-). Java 8 has unfortunately implemented a very limited library supporting optional.

    As Java programmers we should only be using null to interact with legacy libraries.

    0 讨论(0)
  • 2020-11-22 12:29

    My take is that Optional should be a Monad and these are not conceivable in Java.

    In functional programming you deal with pure and higher order functions that take and compose their arguments only based on their "business domain type". Composing functions that feed on, or whose computation should be reported to, the real-world (so called side effects) requires the application of functions that take care of automatically unpacking the values out of the monads representing the outside world (State, Configuration, Futures, Maybe, Either, Writer, etc...); this is called lifting. You can think of it as a kind of separation of concerns.

    Mixing these two levels of abstraction doesn't facilitate legibility so you're better off just avoiding it.

    0 讨论(0)
提交回复
热议问题