Objects.requireNonNullElse()
Get a non-null value with a clear default, no ternary needed.
Porównanie kodu
✕ Java 8
String name = input != null
? input
: "default";
// easy to get the order wrong
✓ Java 9+
String name = Objects
.requireNonNullElse(
input, "default"
);
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
Clear intent
Method name describes exactly what it does.
Null-safe default
The default value is also checked for null.
Readable
Better than ternary for simple null-or-default logic.
Stare podejście
Ternary Null Check
Nowoczesne podejście
requireNonNullElse()
Od JDK
9
Poziom trudności
Początkujący
Wsparcie JDK
Objects.requireNonNullElse()
Dostępne
Widely available since JDK 9 (Sept 2017)
Jak to działa
requireNonNullElse returns the first argument if non-null, otherwise the second. The default itself cannot be null — it throws NPE if both are null, catching bugs early.
Powiązana dokumentacja