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

前端 未结 20 2004
我寻月下人不归
我寻月下人不归 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

    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 p1 = otherObject.getP1();
    Optional p2 = otherObject.getP2();
    
    MyCalculator mc = new MyCalculator();
    p1.map(mc::setP1);
    p2.map(mc::setP2);
    int result = mc.calculate();
    

提交回复
热议问题