rspec/rules/S6210/java/rule.adoc

49 lines
1.6 KiB
Plaintext
Raw 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.

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 initialization
* besides this, there is no access to private members through ``++this++``
* there are other statements in the constructor (case covered by S6207: redundant constructors in records)
== Noncompliant Code Example
----
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
----
record Person(String name, int age) {
  Person { // Compliant
if (age < 0) {
throw new IllegalArgumentException("Negative age");
}
  }
}
----
== See
* https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-8.10[Records specification]