I'm learning about Optional<>
used in implementation with JPA and Hibernate. And I see a lot of developers are using these 2 methods isEmpty() or isPresent() like here:
private void checkCustomer(UUID customerId) {
Optional<Customer> customer = customerRepository.findCustomer(customerId);
if (customer.isEmpty()) {
log.warn("Could not find customer with customer id: {}", customerId);
throw new CustomerException(...);
}
}
I want to know if this isEmpty() method checks if the customer is null or empty. For example if there is no customer with this id in the database, then the variable customer will be null or empty? I ask that because if the isEmpty() method checks if the customer is empty, but the customer is null, in this case can I get a NullPointerException at this line customer.isEmpty()
? Or if I use customer.isPresent()
can I get a NullPointerException?
CodePudding user response:
In general, Optional.isEmpty()
and Optional.isPresent()
will not throw NullPointerException by themselves.
However, you need to verify that Optional<Customer> customer
variable is actually receiving Optional<>
value from returning method. In case the method returns null
the exception will be thrown
CodePudding user response:
In a nutshell, Optional
is a container of data wrapped around something nullable, so you can safely interact with it and the wrapped value.
Optional is supposed to have two states: either contain a value, or not. An empty optional represents the absence of data (which can also represented with a null
value in a code which doesn't uses Optional).
Like any other object, optional might be assigned with a value of null
, but it goes against the design goal of the goal of the Optional type. That's something that should never be the case, if your methods are properly designed, don't return null
instead of an empty optional.
You might be interested in reading: