-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathcompact-canonical-constructor.yaml
More file actions
60 lines (60 loc) · 2.01 KB
/
compact-canonical-constructor.yaml
File metadata and controls
60 lines (60 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
---
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,
List<String> pets) {
// Full canonical constructor
public Person(String name,
List<String> pets) {
Objects.requireNonNull(name);
this.name = name;
this.pets = List.copyOf(pets);
}
}
modernCode: |-
public record Person(String name,
List<String> pets) {
// Compact constructor
public Person {
Objects.requireNonNull(name);
pets = List.copyOf(pets);
}
}
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: "language/call-c-from-java"
related:
- "language/records-for-data-classes"
- "language/flexible-constructor-bodies"
- "errors/record-based-errors"
docs:
- title: "Record (Java 21)"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Record.html"
- title: "JEP 395: Records"
href: "https://openjdk.org/jeps/395"