rspec/rules/S6104/java/rule.adoc

48 lines
1.6 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.

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
----
map.computeIfAbsent(key, k -> null); // Noncompliant, the map will not contain an entry key->null.
map.computeIfPresent(key, (k, oldValue) -> null); // Noncompliant
----
== Compliant Solution
----
if (!map.containsKey(key)) {
map.put(key, null);
}
if (map.containsKey(key)) {
map.put(key, null);
}
----
== See Also
* 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)
include::message.adoc[]
include::highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]