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

前端 未结 20 1853
我寻月下人不归
我寻月下人不归 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条回答
  •  -上瘾入骨i
    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.

提交回复
热议问题