
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.
63 lines
1.8 KiB
Plaintext
63 lines
1.8 KiB
Plaintext
== 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[]
|