forked from javaevolved/javaevolved.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptional-chaining.json
More file actions
50 lines (50 loc) · 1.69 KB
/
Copy pathoptional-chaining.json
File metadata and controls
50 lines (50 loc) · 1.69 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
{
"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;\nif (user != null) {\n Address addr = user.getAddress();\n if (addr != null) {\n city = addr.getCity();\n }\n}\nif (city == null) city = \"Unknown\";",
"modernCode": "String city = Optional.ofNullable(user)\n .map(User::address)\n .map(Address::city)\n .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"
}
]
}