Optional chaining
Replace nested null checks with an Optional pipeline.
Porównanie kodu
✕ Java 8
String city = null;
if (user != null) {
Address addr = user.getAddress();
if (addr != null) {
city = addr.getCity();
}
}
if (city == null) city = "Unknown";
✓ Java 9+
String city = Optional.ofNullable(user)
.map(User::address)
.map(Address::city)
.orElse("Unknown");
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
Chainable
Each .map() step handles null transparently.
Linear flow
Read left-to-right instead of nested if-blocks.
NPE-proof
null is handled at each step — no crash possible.
Stare podejście
Nested Null Checks
Nowoczesne podejście
Optional Pipeline
Od JDK
9
Poziom trudności
Początkujący
Wsparcie JDK
Optional chaining
Dostępne
Available since JDK 8+ (improved in 9+)
Jak to działa
Optional.map() chains through nullable values, short-circuiting on the first null. orElse() provides the default. This eliminates pyramid-of-doom null checking.
Powiązana dokumentacja