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

74 lines
1.8 KiB
Plaintext
Raw Permalink 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?
It's a common pattern to test the result of a ``++java.util.Map.get()++`` against ``++null++`` or calling ``++java.util.Map.containsKey()++`` before proceeding with adding or changing the value in the map. However the ``++java.util.Map++`` API offers a significantly better alternative in the form of the ``++computeIfPresent()++`` and ``++computeIfAbsent()++`` methods. Using these instead leads to cleaner and more readable code.
*Note* that this rule is automatically disabled when the project's ``++sonar.java.source++`` is not 8.
=== Noncompliant code example
[source,java]
----
V value = map.get(key);
if (value == null) { // Noncompliant
value = V.createFor(key);
if (value != null) {
map.put(key, value);
}
}
if (!map.containsKey(key)) { // Noncompliant
value = V.createFor(key);
if (value != null) {
map.put(key, value);
}
}
return value;
----
=== Compliant solution
[source,java]
----
return map.computeIfAbsent(key, k -> V.createFor(k));
----
=== Exceptions
This rule will not raise an issue when trying to add ``++null++`` to a map, because ``++computeIfAbsent++`` will not add the entry if the value returned by the function is ``++null++``.
== Resources
=== Related rules
* S6104 - Map "computeIfAbsent()" and "computeIfPresent()" should not be used to add "null" values.
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Replace this ("Map.get()" and condition | "Map.containsKey()") with a call to ("Map.computeIfAbsent()" | "Map.computeIfPresent()").
=== Highlighting
Primary: condition
Secondary: ``++Map.get++`` call or ``++Map.containsKey++`` call
'''
== Comments And Links
(visible only on this page)
=== is related to: S6104
endif::env-github,rspecator-view[]