rspec/rules/S6210/java/rule.adoc
Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
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.
2023-05-25 14:18:12 +02:00

70 lines
2.0 KiB
Plaintext
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

== 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[]