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

前端 未结 20 1617
我寻月下人不归
我寻月下人不归 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: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) {
        // 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

提交回复
热议问题