rspec/rules/S6215/java/rule.adoc

67 lines
2.0 KiB
Plaintext
Raw 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)
include::message.adoc[]
include::highlighting.adoc[]
endif::env-github,rspecator-view[]