GotchaDifficulty: Advanced1 min

Optional.get() Without a Check Brings the Null Bug Back

Absence made impossible to ignore, and ignored anyway with one method call.

get() returns the value inside an Optional and throws NoSuchElementException when there is none. Calling it without checking first is as unsafe as using a reference without checking for null: a different exception, in the same place, for the same reason.

A method returns Optional so that absence cannot be ignored. The caller writes one more method call than they would have, and ignores it anyway:

java
String name = findByReference(ref).get().name();
text
Exception in thread "main" java.util.NoSuchElementException: No value present

The trace is identical in shape to the null version: the failure happens at the call site that assumed a value, and the stack trace does not say why the value was missing.

What the Optional bought, and what get() gave back
Compared onReturning nullReturning Optional, then get()
Signature warns the callerNoYes
Compiler forces a checkNoNo
Failure when absentNullPointerExceptionNoSuchElementException

Reach for map, orElse, orElseGet, ifPresent or orElseThrow with a message. orElseThrow() is the honest spelling when you genuinely believe it cannot be empty, because the name says what will happen if you are wrong.