Optional
15 questions in 4 subtopics.
Optional usage
What problem does Optional solve, and what are the differences betweenorElse, orElseGet, orElseThrow and or?Rewrite using Optional without get():User u = repo.findById(id);
if (u != null && u.getAddress() != null) {
return u.getAddress().getCity();
}
return "unknown";
findById now returns Optional<User>.A service is slow and a profile shows a remote call inside this line: Config c = cache.get(key).orElse(loadFromRemote(key)); Explain the bug.Optional, nullness annotations and Kotlin's nullable types all address the same problem in different ways. For a company with Java and Kotlin services sharing libraries, what long-term null-handling strategy do you choose, and how do you keep it consistent across languages?Optional anti-patterns
List common Optional anti-patterns and explain why each is a problem.Optional is a value-based class. What does that mean, and why should code not use == or synchronize on Optional instances?A teammate makes every entity field Optional and every method parameter Optional to remove nulls from a codebase. Review this approach.Code reviews across teams keep findingOptional.get() without checks, Optional fields and orElse with expensive calls. How would you reduce these problems at scale?Optional vs null in APIs
You are designing a public library API. When should a method returnOptional<T>, return null, throw an exception, or return a default object?You are designing the repository and service interfaces of a shared domain library used by twenty teams. Specify where Optional is allowed and where it is not, and how changes to these signatures are handled for compatibility.Across your organisation, some libraries return Optional, some return null with @Nullable and Kotlin teams consume both. What single convention would you set and how would you enforce it?Optional was designed as a limited return-type tool, yet many teams expected it to remove nulls from Java. Why was it designed this way, and how does that shape your strategy for null safety over the next years?Optional in streams
GivenList<String> ids and a method Optional<User> find(String id), get a list of the users that exist. Show the Java 9 approach and an earlier one.Which stream terminal operations return Optional and why? Why does max on an empty stream return Optional rather than null?Looking at a decade of Java code, Optional and streams together created both clearer code and new kinds of confusing chains. What would you include in a long-lived style guide for combining them, and why?No question matches these choices.