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

63 lines
1.8 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?
Map https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function-[computeIfAbsent] and https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfPresent-K-java.util.function.BiFunction-[computeIfPresent] methods are convenient to avoid the cumbersome process to check if a key exists or not, followed by the addition of the entry. However, when the function used to compute the value returns ``++null++``, the entry ``++key->null++`` will not be added to the Map. Furthermore, in the case of ``++computeIfPresent++``, if the key is present the entry will be removed. These methods should therefore not be used to conditionally add an entry with a null value. The traditional way should be used instead.
This rule raises an issue when ``++computeIfAbsent++`` or ``++computeIfPresent++`` is used with a lambda always returning null.
=== Noncompliant code example
[source,java]
----
map.computeIfAbsent(key, k -> null); // Noncompliant, the map will not contain an entry key->null.
map.computeIfPresent(key, (k, oldValue) -> null); // Noncompliant
----
=== Compliant solution
[source,java]
----
if (!map.containsKey(key)) {
map.put(key, null);
}
if (map.containsKey(key)) {
map.put(key, null);
}
----
== Resources
=== Related rules
* S3824 - "Map.get" and value test should be replaced with a single method call
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Use "Map.containsKey(key)" followed by "Map.put(key, null)" to add null values.
=== Highlighting
* Primary: computeIfAbsent method name
* Secondary: null literal in the argument.
** Message: The entry will not be put into the Map.
'''
== Comments And Links
(visible only on this page)
=== relates to: S3824
endif::env-github,rspecator-view[]