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

前端 未结 6 2129
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:23

    In brief: avoid the Optional type. The main argument for Optional on return types is, "It's too easy for clients to forget to handle the possibility of a null return value. Optional is ugly and in your face, so a client is less likely to forget to handle the possibility of an empty return value. Everywhere else, programmers should continue to use normal references, which might be null."

    I wrote a discussion of the pros and cons of using Java's Optional type: Nothing is better than the Optional type.

提交回复
热议问题