I have a question regarding Java 8\'s Optional, the purpose of which is to tackle NullPointerException
exceptions.
The question is, what is the reason for h
After reading some answers and comments I think this explanation is missing. Consider a method like
public Optional name(Customer c) {
return c.isNew() ? Optional.ofNullable(getName(c)) : Optional.of(getName(c));
}
Here you want to throw a NullPointerException
if the customer isn't new and is supposed to have a name; your code is inconsistent if that's ever null
. Yet the name may not yet exist if the customer is new, hence ofNullable
in that case and the method returns Optional
.