Optional
type introduced in Java 8 is a new thing for many developers.
Is a getter method returning Optional<Foo>
type in place of the classic Foo
a good practice? Assume that the value can be null
.
Conclusion While we can use Optional type as a hint that there might be no non-null value, we should be careful not to overuse the Optional return type, particularly in a getter of an entity bean or a DTO. The source code of the examples in this tutorial can be found on GitHub.
Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value.
Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values. It is introduced in Java 8 and is similar to what Optional is in Guava.
By the way, here is how Optional is described in the Java SE 11 documentation: “ Optional is primarily intended for use as a method return type where there is a clear need to represent 'no result,' and where using null is likely to cause errors.
Of course, people will do what they want. But we did have a clear intention when adding this feature, and it was not to be a general purpose Maybe type, as much as many people would have liked us to do so. Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent "no result", and using null
for such was overwhelmingly likely to cause errors.
For example, you probably should never use it for something that returns an array of results, or a list of results; instead return an empty array or list. You should almost never use it as a field of something or a method parameter.
I think routinely using it as a return value for getters would definitely be over-use.
There's nothing wrong with Optional that it should be avoided, it's just not what many people wish it were, and accordingly we were fairly concerned about the risk of zealous over-use.
(Public service announcement: NEVER call Optional.get
unless you can prove it will never be null; instead use one of the safe methods like orElse
or ifPresent
. In retrospect, we should have called get
something like getOrElseThrowNoSuchElementException
or something that made it far clearer that this was a highly dangerous method that undermined the whole purpose of Optional
in the first place. Lesson learned. (UPDATE: Java 10 has Optional.orElseThrow()
, which is semantically equivalent to get()
, but whose name is more appropriate.))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With