-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathcompact-canonical-constructor.json
More file actions
44 lines (44 loc) · 2.01 KB
/
compact-canonical-constructor.json
File metadata and controls
44 lines (44 loc) · 2.01 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
{
"id": 95,
"slug": "compact-canonical-constructor",
"title": "Compact canonical constructor",
"category": "language",
"difficulty": "intermediate",
"jdkVersion": "16",
"oldLabel": "Java 16",
"modernLabel": "Java 16+",
"oldApproach": "Explicit constructor validation",
"modernApproach": "Compact constructor",
"oldCode": "public record Person(String name,\n List<String> pets) {\n // Full canonical constructor\n public Person(String name,\n List<String> pets) {\n Objects.requireNonNull(name);\n this.name = name;\n this.pets = List.copyOf(pets);\n }\n}",
"modernCode": "public record Person(String name,\n List<String> pets) {\n // Compact constructor\n public Person {\n Objects.requireNonNull(name);\n pets = List.copyOf(pets);\n }\n}",
"summary": "Validate and normalize record fields without repeating parameter lists.",
"explanation": "Records can declare a compact canonical constructor that omits the parameter list and field assignments. The compiler automatically assigns parameters to fields after your validation logic runs. This is ideal for precondition checks, defensive copies, and normalization.",
"whyModernWins": [
{
"icon": "✂️",
"title": "Less repetition",
"desc": "No need to repeat parameter list or assign each field manually."
},
{
"icon": "🛡️",
"title": "Validation",
"desc": "Perfect for null checks, range validation, and defensive copies."
},
{
"icon": "📖",
"title": "Clearer intent",
"desc": "Compact syntax emphasizes validation, not boilerplate."
}
],
"support": {
"state": "available",
"description": "Widely available since JDK 16 (March 2021)"
},
"prev": "language/static-members-in-inner-classes",
"next": "enterprise/servlet-vs-jaxrs",
"related": [
"language/records-for-data-classes",
"language/flexible-constructor-bodies",
"errors/record-based-errors"
]
}