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

44 lines
1.6 KiB
Plaintext

== Why is this an issue?
It is very common to pass a collection constructor reference as an argument, for example ``++Collectors.toCollection(ArrayList::new)++`` takes the ``++ArrayList::new++`` constructor. When the method expects a ``++java.util.function.Supplier++`` it is perfectly fine. However when the method argument type is ``++java.util.function.Function++`` it means that an argument will be passed to the constructor.
The first argument of Collections constructors is usually an integer representing its "initial capacity". This is generally not what the developer expects, but the memory allocation is not visible at first glance.
This rule raises an issue when a collection constructor is passed by reference as a ``++java.util.function.Function++`` argument.
=== Noncompliant code example
[source,java]
----
Arrays.asList(1, 2, 54000).stream().collect(Collectors.toMap(Function.identity(), ArrayList::new)); // Noncompliant, "ArrayList::new" unintentionally refers to "ArrayList(int initialCapacity)" instead of "ArrayList()"
----
=== Compliant solution
[source,java]
----
Arrays.asList(1, 2, 54000).stream().collect(Collectors.toMap(Function.identity(), id -> new ArrayList<>())); // Compliant, explicitly show the usage of "id -> new ArrayList<>()" or "id -> new ArrayList<>(id)"
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Replace this constructor reference with a lambda returning a new ``++List/HashMap/...++``.
=== Highlighting
The constructor reference.
endif::env-github,rspecator-view[]