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> customer = Optional.empty();
....
vs
public class Transaction {
private Customer 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.