Is using Optional.ofNullable as a replacement for the ternary operator a good practice?

前端 未结 6 2141
Happy的楠姐
Happy的楠姐 2020-12-09 04:50

Consider the usage of this expression:

String hi = Optional.ofNullable(sayHi()).orElse(\"-\");

which effectively corresponds to this ternar

6条回答
  •  感动是毒
    2020-12-09 05:40

    If you're going to allow Optional into your workflow then you should consider modifying the sayHi() method so that it returns Optional which will make the result more elegant:

    hi = sayHi().orElse("-");
    

    If you don't want to introduce Optional into your workflow (because it does create an additional object to contain the optional value) then you're better off sticking with simple null checks and the ternary operator.

    With regard to the performance costs of Optional (such as increased garbage collection), you'd need to profile your application and decide whether or not this was a real concern.

    Additionally, if you're mostly interested in String then be aware of the Objects.toString(Object, String) method which return a default value if the object is null:

    hi = Objects.toString(hi, "-");
    

    This is tidier and more elegant than writing out the code manually.

提交回复
热议问题