rspec/rules/S6215/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

74 lines
2.1 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?
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[]