Quick revision
The short answer
I would move the problem from code review into the build: static analysis such as IntelliJ inspections, Error Prone or ArchUnit rules flags unchecked get(), Optional fields and orElse with expensive calls in CI. Alongside it, a one-page guide shows the preferred methods with examples, including orElseThrow() in place of get() so intent is explicit. I would fix shared libraries first, because other teams copy their style, and track the count of flagged patterns per repository so we can see progress and stop regressions.
What to remember
In this answer, we saw that recurring review findings call for a system rather than more reminders. Static analysis in CI, introduced as warnings with a baseline and then as errors for new code, catches get() without checks, Optional fields and orElse with expensive arguments. A one-page guide with examples tells developers what to write instead, with orElseThrow() replacing get(). Fixing shared libraries and templates first stops the patterns from spreading, and tracking counts per repository shows progress and prevents regressions.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
I would move the problem from code review into the build: static analysis such as IntelliJ inspections, Error Prone or ArchUnit rules flags unchecked get(), Optional fields and orElse with expensive calls in CI. Alongside it, a one-page guide shows the preferred methods with examples, including orElseThrow() in place of get() so intent is explicit. I would fix shared libraries first, because other teams copy their style, and track the count of flagged patterns per repository so we can see progress and stop regressions.
Why this question is asked
When the same three comments appear in code reviews across many teams, the problem is no longer individual developers; it is the system that lets the patterns in. Reviewers get tired of repeating themselves, some reviews miss the issue, and new code copies old code. Interviewers ask this leadership question to see whether we can turn a recurring review finding into a lasting fix at organisation scale, without heavy process. In this answer, we will recap why the three patterns are harmful, then go through the tools, the guide, the order in which to fix code, and how to measure whether it is working.
1A Quick Recap of the Three Patterns
Optional.get() returns the value or throws NoSuchElementException when the Optional is empty, so calling it without a check is a null dereference with a different name. Optional fields go against the type's design: Optional is not Serializable, JPA does not map it, and every instance is an extra object. The third pattern is the most subtle, because it looks correct.
The reason is ordinary Java evaluation: the argument of orElse is computed before orElse is called, whether or not it will be used. With a remote call as the argument, every cache hit still pays for an HTTP request. In one service this can double the load on a downstream system without anyone noticing, because the result is always correct.
2Let the Build Find the Patterns
Review comments do not scale; automated checks do. All three patterns are mechanical enough for tools to detect. IntelliJ IDEA has inspections for Optional.get() without an isPresent() check and for Optional used as a field or parameter type, and the same inspections can run in CI through JetBrains Qodana. Error Prone and SonarQube rules cover similar ground; check which built-in checks your versions include, and fill gaps with small custom rules. Structural rules, such as "no field may have type Optional", are easy to express in ArchUnit as an ordinary unit test.
I would introduce the checks as warnings for a few weeks, so teams see the findings without blocked builds, and then switch new violations to errors. Existing violations go into a baseline file, so the build fails only when someone adds a new one. That keeps the rollout cheap and avoids a big-bang cleanup that nobody has time for.
3A One-Page Guide With Examples
Tools tell people what is wrong; a guide tells them what to write instead. I would keep it to one page, because longer guides are not read, and every rule would have a short before and after example from our own code. The guide answers the question developers actually have in front of them: "I have an Optional, what method do I call?"
One rule deserves emphasis: use orElseThrow() instead of get(). They behave the same, but orElseThrow() says that throwing is intended, while get() hides whether the author checked or forgot. Since Java 10 the no-argument orElseThrow() exists precisely for this reason, and it lets the static check ban get() completely with no exceptions.
| When you want to | Write | Instead of |
|---|---|---|
| Fail if missing | opt.orElseThrow(() -> new NotFound(id)) | opt.get() |
| Use a constant fallback | opt.orElse("guest") | isPresent() ? get() : "guest" |
| Use a computed fallback | opt.orElseGet(() -> load()) | opt.orElse(load()) |
| Transform the value | opt.map(User::name) | get() inside an if |
| Act only if present | opt.ifPresent(this::notify) | if (isPresent()) notify(get()) |
| Store an optional value | nullable field + Optional getter | Optional<T> field |
4Fix Shared Libraries First
Where we start matters. Developers learn style by copying the code they use most, and the code they use most is in shared libraries, platform starters and internal templates. If the shared customer client returns entities with Optional fields, every team that builds on it will think that is the house style.
So the first cleanup happens in the libraries that most services depend on, and in the project templates new services are generated from. These changes also carry the most weight per line fixed: one corrected template influences every service created afterwards. Application code can then be cleaned up gradually, mostly when teams touch the files anyway, with the baseline preventing new violations in the meantime.
5Measure Progress and Stop Regressions
To know whether this works, I would track the number of flagged patterns per repository, taken from the static analysis results, and show the trend on a simple dashboard. The goal is not a perfect zero by a deadline; it is that the line goes down and never up. A count also helps prioritise: if one repository has 300 findings and the rest have ten, that team may need a pairing session rather than another reminder.
After a few months I would also check the review comments themselves. If reviewers no longer write "use orElseGet here", the checks are doing their job and reviewers can spend their attention on design instead.
- Enable checks as warningsIDE inspections, ArchUnit, Error Prone
- Baseline existing findingsbuild ignores old violations
- Publish the one-page guideexamples from our own code
- Fix shared libraries and templatesmost copied code first
- Turn new violations into errorsCI blocks regressions
- Track counts per repositorytrend must go down
6 steps in order. Play them, or step through them one at a time.
6Follow-up questions
Would you ban Optional.get() completely?
Yes, in favour of orElseThrow(), because the two are identical in behaviour and the second states the intent. A complete ban also makes the static check simple: no exceptions to reason about, no suppression comments to review.
What if teams push back that the checks slow them down?
The baseline answers most of that, since nobody is forced to fix old code. For new code, the fix for each finding is usually one line, and the guide shows it. I would also listen for false positives and remove or adjust any rule that produces them, because a noisy check loses trust quickly.
Why not simply run a mass automated fix?
Some patterns can be fixed automatically, such as get() to orElseThrow(), and tools like OpenRewrite can do it safely. Others need judgement: replacing an Optional field changes a class's API and its mapping. I would automate the mechanical ones and leave the rest to the baseline and gradual cleanup.
7Conclusion
In this answer, we saw that recurring review findings call for a system rather than more reminders. Static analysis in CI, introduced as warnings with a baseline and then as errors for new code, catches get() without checks, Optional fields and orElse with expensive arguments. A one-page guide with examples tells developers what to write instead, with orElseThrow() replacing get(). Fixing shared libraries and templates first stops the patterns from spreading, and tracking counts per repository shows progress and prevents regressions.
Open with
When the same comments show up in reviews across teams, I treat it as a tooling problem, not a people problem. First, I'd make the build catch the patterns: IntelliJ inspections run in CI through Qodana, Error Prone or Sonar rules where they exist, and a simple ArchUnit test that no field has type Optional.
Then, if they want more
I'd start them as warnings, baseline the existing findings so only new violations fail, and then make new violations errors. Second, a one-page guide with before and after examples from our own code, answering what to call when you have an Optional.
The key rules are orElseThrow instead of get, because it makes intent explicit and lets us ban get entirely, and orElseGet instead of orElse when the fallback is expensive, since orElse evaluates its argument every time, which in one case meant an HTTP call on every cache hit.
Third, I'd fix the shared libraries and service templates first, because teams copy the style of the code they depend on, so those fixes spread. Finally, I'd track the count of findings per repository on a dashboard.
I'm not aiming for zero by a date; I want the trend down and never up, and I'd consider it working when reviewers stop writing these comments.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 10
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.stream, package documentation, java.util.function, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Code reviews across teams keep finding Optional.get() without checks, Optional fields...": https://scrivio-interview-library.netlify.app/java/optional/d12f6d46e2/