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

62 lines
1.7 KiB
Plaintext

== Why is this an issue?
Passing single ``++null++`` or primitive array argument to the variable arity method may not work as expected. In the case of ``++null++``, it is not passed as array with single element, but the argument itself is ``++null++``. In the case of a primitive array, if the formal parameter is ``++Object...++``, it is passed as a single element array. This may not be obvious to someone not familiar with such corner cases, and it is probably better to avoid such ambiguities by explicitly casting the argument to the desired type.
=== Noncompliant code example
[source,java]
----
class A {
public static void main(String[] args) {
vararg(null); // Noncompliant, prints "null"
int[] arr = {1,2,3};
vararg(arr); // Noncompliant, prints "length: 1"
}
static void vararg(Object... s) {
if (s == null) {
System.out.println("null");
} else {
System.out.println("length: " + s.length);
}
}
}
----
=== Compliant solution
[source,java]
----
class A {
public static void main(String[] args) {
vararg((Object) null); // prints 1
Object[] arr = {1,2,3};
vararg(arr); // prints 3
}
static void vararg(Object... s) {
if (s == null) {
System.out.println("null"); // not reached
} else {
System.out.println("length: " + s.length);
}
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* default case: Cast this argument to '<Type>' to pass a single element to the vararg method.
* primitive vararg passed 'null': Remove this argument or pass an empty 'int' array to the vararg method.
endif::env-github,rspecator-view[]