Uses for Optional

前端 未结 14 1414
眼角桃花
眼角桃花 2020-11-22 01:01

Having been using Java 8 now for 6+ months or so, I\'m pretty happy with the new API changes. One area I\'m still not confident in is when to use Optional. I se

14条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 01:23

    In java, just don't use them unless you are addicted to functional programming.

    They have no place as method arguments (I promess someone one day will pass you a null optional, not just an optional that is empty).

    They make sense for return values but they invite the client class to keep on stretching the behavior-building chain.

    FP and chains have little place in an imperative language like java because it makes it very hard to debug, not just to read. When you step to the line, you can't know the state nor intent of the program; you have to step into to figure it out (into code that often isn't yours and many stack frames deep despite step filters) and you have to add lots of breakpoints down to make sure it can stop in the code/lambda you added, instead of simply walking the if/else/call trivial lines.

    If you want functional programming, pick something else than java and hope you have the tools for debugging that.

提交回复
热议问题