A map's mapping function returns null, which stores nothing or removes the entry

tx0/java:null-from-computerecommendedwarningbug

What it finds

cache.computeIfAbsent(key, k -> null) does not store null: a mapping function that returns null means "no value", so nothing is added, and computeIfPresent with a function that returns null removes the entry. Code that expects the key to be present afterwards is wrong; put stores a value, and remove removes on purpose.

Reported are lambdas passed as the mapping function of computeIfAbsent, computeIfPresent, compute or merge whose result is the literal null, always or in one of their return statements.

From the rule's source, null_from_compute.rs.

Example from the rule's tests
import java.util.Map; class Cache {  void fill(Map<String, String> cache) {    cache.computeIfAbsent("k", k -> null);tx0 reports: returning null from the function of computeIfAbsent stores nothing    cache.computeIfPresent("k", (k, v) -> {      if (v.isEmpty()) {        return null;tx0 reports: returning null from the function of computeIfPresent removes the entry      }      return v;    });    cache.computeIfAbsent("j", k -> "value");  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/java:null-from-compute" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:null-from-compute] reason="..."

tx0 explain tx0/java:null-from-compute shows the same in the terminal. Found a false positive? Report it.