I have read something about the purpose of Optional
(unfortunately I don't remember where) in Java 8, and I was surprised the writer didn't mention the use of an Optional
as an attribute in a class.
Since I am using optionals pretty frequently in my classes, I was wondering if this is a good practice. Or could I better just use normal attributes, which return null
when they are not set?
Note: It may look like my question is opinion based, but I get the feeling using Optional
in a class is really not the way to go (after reading the mentioned post). However, I like to use it and can't find any downside of using it.
Example
I would like to give an example to clarify. I have a class Transaction
, which is built like this:
public class Transaction {
private Optional<Customer> = Optional.empty();
....
vs
public class Transaction {
private Customer = null;
....
When checking on a Customer
, I think it is most logical to use transaction.getCustomer().isPresent()
than transaction.getCustomer() != null
. In my opinion the first code is cleaner than the second one.
Java 8's Optional
was mainly intended for return values from methods, and not for properties of Java classes, as described in Optional in Java SE 8:
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
orSome
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 usingnull
for such was overwhelmingly likely to cause errors.The key here is the focus on use as a return type. The class is definitively not intended for use as a property of a Java Bean. Witness to this is that
Optional
does not implementSerializable
, which is generally necessary for widespread use as a property of an object.