forked from javaevolved/javaevolved.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptional-chaining.yaml
More file actions
51 lines (51 loc) · 1.45 KB
/
Copy pathoptional-chaining.yaml
File metadata and controls
51 lines (51 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
---
id: 65
slug: "optional-chaining"
title: "Optional chaining"
category: "errors"
difficulty: "beginner"
jdkVersion: "9"
oldLabel: "Java 8"
modernLabel: "Java 9+"
oldApproach: "Nested Null Checks"
modernApproach: "Optional Pipeline"
oldCode: |-
String city = null;
if (user != null) {
Address addr = user.getAddress();
if (addr != null) {
city = addr.getCity();
}
}
if (city == null) city = "Unknown";
modernCode: |-
String city = Optional.ofNullable(user)
.map(User::address)
.map(Address::city)
.orElse("Unknown");
summary: "Replace nested null checks with an Optional pipeline."
explanation: "Optional.map() chains through nullable values, short-circuiting on the\
\ first null. orElse() provides the default. This eliminates pyramid-of-doom null\
\ checking."
whyModernWins:
- icon: "🔗"
title: "Chainable"
desc: "Each .map() step handles null transparently."
- icon: "📖"
title: "Linear flow"
desc: "Read left-to-right instead of nested if-blocks."
- icon: "🛡️"
title: "NPE-proof"
desc: "null is handled at each step — no crash possible."
support:
state: "available"
description: "Available since JDK 8+ (improved in 9+)"
prev: "errors/helpful-npe"
next: "errors/require-nonnull-else"
related:
- "errors/helpful-npe"
- "errors/multi-catch"
- "errors/require-nonnull-else"
docs:
- title: "Optional"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Optional.html"