Code Review Red Flags: Spotting get() Misuse
You'll learn to recognize dangerous Optional patterns during code reviews and recommend safer alternatives.
The Code Reviewer's Eye
When reviewing code that uses Optional, you're looking for patterns that negate its safety benefits. The most common red flag is treating Optional like a fancy null check rather than embracing its functional style. Your goal is to spot where developers have missed opportunities to write safer, clearer code.
Common Red Flags to Watch For
The Classic Anti-Pattern
// RED FLAG: Defeats Optional's purpose
if (optional.isPresent()) {
User user = optional.get();
processUser(user);
}
This is just verbose null-checking in disguise. Suggest ifPresent() instead.
Naked get() Calls
// RED FLAG: NoSuchElementException waiting to happen
String name = findUserName().get();
If the value is genuinely required, suggest orElseThrow() with a meaningful exception.
Unnecessary Checks Before Safe Operations
// RED FLAG: Redundant isPresent() before orElse()
if (optional.isPresent()) {
return optional.get();
} else {
return defaultValue;
}
This should simply be optional.orElse(defaultValue).
get() in Return Statements
// RED FLAG: Assumes presence without justification
return findUser(id).get();
Unless presence is guaranteed (and documented why), this is dangerous.
What to Recommend
Point reviewers toward orElse(), orElseGet(), orElseThrow(), ifPresent(), map(), or flatMap() depending on context. Ask: "What should happen if the value is absent?"
Key Takeaway: During code reviews, any appearance of .get() should trigger scrutiny—it usually indicates the developer hasn't fully embraced Optional's design intent and may have introduced hidden exception risks.