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

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

    Accepting Optional as parameters causes unnecessary wrapping at caller level.

    For example in the case of:

    public int calculateSomething(Optional p1, Optional p2 {}
    

    Suppose you have two not-null strings (ie. returned from some other method):

    String p1 = "p1"; 
    String p2 = "p2";
    

    You're forced to wrap them in Optional even if you know they are not Empty.

    This get even worse when you have to compose with other "mappable" structures, ie. Eithers:

    Either value = compute().right().map((s) -> calculateSomething(
    < here you have to wrap the parameter in a Optional even if you know it's a 
      string >));
    

    ref:

    methods shouldn't expect Option as parameters, this is almost always a code smell that indicated a leakage of control flow from the caller to the callee, it should be responsibility of the caller to check the content of an Option

    ref. https://github.com/teamdigitale/digital-citizenship-functions/pull/148#discussion_r170862749

提交回复
热议问题