2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-07-12 18:36:31 +02:00
In Java 16 records represent a brief notation for immutable data structures. Records have autogenerated implementations for constructors with all parameters, ``++getters++``, ``++equals++``, ``++hashcode++`` and ``++toString++``. Although these methods can still be overridden inside records, there is no use to do so if no special logic is required.
2021-04-28 16:49:39 +02:00
This rule reports an issue on empty compact constructors, trivial canonical constructors and simple getter methods with no additional logic.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
2021-07-12 18:36:31 +02:00
record Person(String name, int age) {
Person(String name, int age) { // Noncompliant, already autogenerated
this.name = name;
this.age = age;
}
2021-04-28 16:49:39 +02:00
}
2021-07-12 18:36:31 +02:00
record Person(String name, int age) {
Person { // Noncompliant, no need for empty compact constructor
}
public String name() { // Noncompliant, already autogenerated
2021-04-28 16:49:39 +02:00
return name;
}
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
2021-07-12 18:36:31 +02:00
record Person(String name, int age) { } // Compliant
2021-04-28 16:49:39 +02:00
2021-07-12 18:36:31 +02:00
record Person(String name, int age) {
Person(String name, int age) { // Compliant
this.name = name.toLowerCase(Locale.ROOT);
this.age = age;
}
2021-04-28 16:49:39 +02:00
}
2021-07-12 18:36:31 +02:00
record Person(String name, int age) {
Person { // Compliant
2021-04-28 16:49:39 +02:00
if (age < 0) {
throw new IllegalArgumentException("Negative age");
2021-07-12 18:36:31 +02:00
}
}
2021-04-28 16:49:39 +02:00
public String name() { // Compliant
return name.toUpperCase(Locale.ROOT);
}
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
== Resources
2021-04-28 16:49:39 +02:00
2021-07-06 17:15:17 +02:00
* https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-8.10[Records specification]
2021-04-28 18:08:03 +02:00
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Remove this redundant constructor/method which is the same as a default one
=== Highlighting
method name
2021-09-20 15:38:42 +02:00
endif::env-github,rspecator-view[]