
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
70 lines
2.0 KiB
Plaintext
70 lines
2.0 KiB
Plaintext
== Why is this an issue?
|
||
|
||
In records, introduced in Java 16, there are 2 ways to write a custom constructor: canonical and compact.
|
||
|
||
|
||
A canonical constructor is an ordinary constructor with arguments for all private fields. The default implementation just provides initialization for all private fields and there is no need to write it manually. You might want to write it yourself when you need to customize the constructor logic.
|
||
|
||
|
||
A compact constructor doesn't have parameters defined explicitly, parentheses are omitted and access to private fields is not possible (even via ``++this++``). The compact constructor has access to the constructor's arguments and its body is executed right before the field initialization. It's a perfect place to provide validation.
|
||
|
||
|
||
This rule reports an issue when a canonical constructor can be easily replaced by a compact version when these requirements are met:
|
||
|
||
* the last statements are trivial field initializations
|
||
* no statement reads from fields or components
|
||
* there are other statements in the constructor (case covered by S6207: redundant constructors in records)
|
||
|
||
|
||
=== Noncompliant code example
|
||
|
||
[source,java]
|
||
----
|
||
record Person(String name, int age) {
|
||
Person(String name, int age) { // Noncompliant
|
||
if (age < 0) {
|
||
throw new IllegalArgumentException("Negative age");
|
||
}
|
||
this.name = name;
|
||
this.age = age;
|
||
}
|
||
}
|
||
----
|
||
|
||
|
||
=== Compliant solution
|
||
|
||
[source,java]
|
||
----
|
||
record Person(String name, int age) {
|
||
Person { // Compliant
|
||
if (age < 0) {
|
||
throw new IllegalArgumentException("Negative age");
|
||
}
|
||
}
|
||
}
|
||
----
|
||
|
||
|
||
== Resources
|
||
|
||
* https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-8.10[Records specification]
|
||
|
||
ifdef::env-github,rspecator-view[]
|
||
|
||
'''
|
||
== Implementation Specification
|
||
(visible only on this page)
|
||
|
||
=== Message
|
||
|
||
Replace this usage of a 'canonical' constructor with a more concise 'compact' version
|
||
|
||
|
||
=== Highlighting
|
||
|
||
canonical constructor declaration
|
||
|
||
|
||
endif::env-github,rspecator-view[]
|