
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.
74 lines
2.1 KiB
Plaintext
74 lines
2.1 KiB
Plaintext
== Why is this an issue?
|
||
|
||
Sometimes when implementing a method, there is a need to return more than one value. To reduce the boilerplate of describing another class, other programming languages introduced such structures as ``++Pair++``, ``++Tuple++``, ``++Vector++``, etc.
|
||
|
||
Unfortunately, in Java, there is no such structure and ``++Map.Entry++`` or ``++Object[]++`` of fixed size are used as a workaround for returning multiple values from a method.
|
||
|
||
|
||
Java 16 introduced records to represent immutable data structures and they can be used for grouping different values in one entity. By using records, developers will have meaningful names and result in a more readable code. Furthermore, when using ``++Object[]++``, there is a risk of getting ``++ClassCastException++`` or ``++ArrayIndexOutOfBoundsException++`` if not used carefully. It means that using records is not only more readable but is definitely safer.
|
||
|
||
|
||
This rule should report an issue when ``++Object[]++`` of a fixed size (< 7) or ``++Map.Entry++`` are returned from a *private* method.
|
||
|
||
|
||
=== Noncompliant code example
|
||
|
||
[source,java]
|
||
----
|
||
private Map.Entry<String, Integer> getPerson() {
|
||
String name = "John";
|
||
int age = 25;
|
||
return Map.entry(name, age); // Noncompliant
|
||
}
|
||
|
||
private Object[] getPerson() {
|
||
Object[] result = new Object[2];
|
||
result[0] = "John";
|
||
result[1] = 25;
|
||
return result; // Noncompliant
|
||
}
|
||
----
|
||
|
||
|
||
=== Compliant solution
|
||
|
||
[source,java]
|
||
----
|
||
record Person(String name, int age) {}
|
||
|
||
Person getPerson() {
|
||
String name = "John";
|
||
int age = 25;
|
||
return new Person(name, age); // Compliant
|
||
}
|
||
----
|
||
|
||
|
||
=== Exceptions
|
||
|
||
If the result of a method returning ``++Map.Entry++`` is actually used in a ``++Map++``. Non-private methods are not taken into consideration.
|
||
|
||
|
||
== 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
|
||
|
||
Refactor this method to return a record instead of "Map.Entry"|"Object[]"
|
||
|
||
|
||
=== Highlighting
|
||
|
||
* Primary: return statement
|
||
* Secondary: returned type and assignments
|
||
|
||
|
||
endif::env-github,rspecator-view[]
|