Video in progress
Why is using Optional.get() dangerous, and what is the difference between orElse() and orElseGet()?
On an empty Optional, get() throws NoSuchElementException, which is just another name for an NPE. With orElse(x), x is always evaluated, while orElseGet(supplier) is called only when the Optional is empty.
📖 Answer
Calling get() without a check defeats the whole idea of Optional. Since Java 10 there's orElseThrow(), which does the same thing but whose name states the intent clearly; I write that.
Now the second part, where many people trip up in interviews:
User u = repo.findById(id).orElse(createDefaultUser());
createDefaultUser() is called even if the user was found, because Java evaluates the argument before passing it to the method. If that method writes to the database or calls an external API, it's extra work and a side effect on every request.
User u = repo.findById(id).orElseGet(this::createDefaultUser); // only when needed
A simple rule:
- a ready constant or a cheap value:
orElse(""),orElse(0),orElse(List.of()); - creating a new object, computing, IO:
orElseGet; - if absence is an error:
orElseThrow(() -> new NotFoundException(...)).
Sign up to mark studied questions and save your progress.