You should almost never call .get(), except in cases where the code path does not allow an empty optional.
Even so, calling .get() on an empty optional is better than handing nulls around. A null may -- by chance, really -- make it several lines down the code, so that the stack trace points you much later in the code than where the null originated. Calling .get() on an empty optional immediately throws a NoSuchElementException, pointing you directly to the line where the optional was empty where it shouldn't have been.
Consider this code:
User user = getUser();
// other stuff here
// ...
// ...
String userSummary = formatUserSummary(user);
// ...
// ...
where public String formatUserSummary(User user){
return "Franchise Location: " +
user.getFranchise().getLocation().getName() +
" Username: " +
user.getUsername();
}
An NPE occurs inside of formatUserSummary. Where did the null come from? Is the user's Franchise null? Maybe the Franchise's Location? Or is it the User that's null?If you instead took an Optional<User>, even if you just immediately unwrapped it with .get(), you'd at least get an error that unambiguously told you that it was the user that was missing.