Should Java 8 getters return optional type?

后端 未结 5 1179
自闭症患者
自闭症患者 2020-11-22 05:42

Optional type introduced in Java 8 is a new thing for many developers.

Is a getter method returning Optional type in place of th

5条回答
  •  情深已故
    2020-11-22 06:16

    After doing a bit of research of my own, I've come across a number of things that might suggest when this is appropriate. The most authoritative being the following quote from an Oracle article:

    "It is important to note that the intention of the Optional class is not to replace every single null reference. Instead, its purpose is to help design more-comprehensible APIs so that by just reading the signature of a method, you can tell whether you can expect an optional value. This forces you to actively unwrap an Optional to deal with the absence of a value." - Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!

    I also found this excerpt from Java 8 Optional: How to use it

    "Optional is not meant to be used in these contexts, as it won't buy us anything:

    • in the domain model layer (not serializable)
    • in DTOs (same reason)
    • in input parameters of methods
    • in constructor parameters"

    Which also seems to raise some valid points.

    I wasn't able to find any negative connotations or red flags to suggest that Optional should be avoided. I think the general idea is, if it's helpful or improves the usability of your API, use it.

提交回复
热议问题