rspec/rules/S6215/java/rule.adoc

67 lines
2.0 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
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
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
----
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
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) {}
Person getPerson() {
String name = "John";
int age = 25;
return new Person(name, age); // Compliant
}
----
=== Exceptions
2021-04-28 16:49:39 +02:00
If the result of a method returning ``++Map.Entry++`` is actually used in a ``++Map++``. Non-private methods are not taken into consideration.
== 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)
include::message.adoc[]
include::highlighting.adoc[]
endif::env-github,rspecator-view[]