Is it a good practice to use Optional as an attribute in a class? [duplicate]
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.
I think it is a theoretical question.
The notion of optional values was brought from functional languages world. Those languages usually also support pattern matching on language level and allow you to pattern match on the optional value.
In functional languages function calls usually return an optional value that other code could pattern match on.
I have never seen passing an optional as argument, but that does not mean it is a bad think. It looks weird though.