rspec/rules/S6206/java/rule.adoc

74 lines
1.5 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
In Java 16 ``++records++`` are finalized and can be safely used in production code. ``++Records++`` represent immutable read-only data structure and should be used instead of creating immutable classes. Immutability of records is guaranteed by the Java language itself, while implementing immutable classes on your own might lead to some bugs.
One of the important aspects of ``++records++`` is that final fields can't be overwritten using reflection.
This rule reports an issue on classes for which all these statements are true:
* all instance fields are private and final
* has only one constructor with a parameter for all fields
* has getters for all fields
=== 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
----
final class Person { // Noncompliant
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {...}
public int getAge() {...}
@Override
public boolean equals(Object o) {...}
@Override
public int hashCode() {...}
@Override
public String toString() {...}
}
----
=== 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
----
record Person(String name, int age) { }
----
== Resources
2021-04-28 16:49:39 +02:00
* 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
Refactor this class declaration to use 'record X(A a, B b)'
=== Highlighting
class declaration
endif::env-github,rspecator-view[]