Errors Początkujący

Use Optional.orElseThrow() as a clearer, intent-revealing alternative to get().

✕ Java 8
// Risky: get() throws if empty, no clear intent
String value = optional.get();

// Verbose: supplier just for NoSuchElementException
String value = optional
    .orElseThrow(NoSuchElementException::new);
✓ Java 10+
// Clear intent: throws NoSuchElementException if empty
String value = optional.orElseThrow();
Widzisz problem z tym kodem? Daj nam znać.
📖

Self-documenting

orElseThrow() clearly signals that absence is unexpected.

🔒

Avoids get()

Static analysis tools flag get() as risky; orElseThrow() is idiomatic.

Less boilerplate

No need to pass a supplier for the default NoSuchElementException.

Stare podejście
get() or orElseThrow(supplier)
Nowoczesne podejście
orElseThrow()
Od JDK
10
Poziom trudności
Początkujący
Optional.orElseThrow() without supplier
Dostępne

Available since JDK 10 (March 2018).

Optional.get() is widely considered a code smell because it hides the possibility of failure. The no-arg orElseThrow(), added in Java 10, does exactly the same thing but makes the intent explicit: the developer expects a value and wants an exception if absent.

Udostępnij 𝕏 🦋 in