Map Compute Function Always Returns Null
ID |
java.map_compute_returns_null |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
collections, reliability |
Description
Reports a Map.computeIfAbsent(key, function) call whose function argument is a lambda that
unconditionally evaluates to null.
Map.computeIfPresent(key, function) is deliberately out of scope: returning null from it is the
documented way to remove the entry, so the same shape there is correct code rather than a defect.
Rationale
computeIfAbsent and computeIfPresent look like a convenient way to conditionally add an
entry with a null value, but neither method behaves that way. When the function returns
null, computeIfAbsent does not add the key → null entry at all, and computeIfPresent
goes further: if the key was present, its entry is removed. A lambda that always returns
null therefore does nothing useful, or actively deletes data, while reading as if it stores
a null.
Map<String, String> cache = new HashMap<>();
cache.computeIfAbsent(key, k -> null); // entry is never added
cache.computeIfPresent(key, (k, old) -> null); // entry is removed if present
A lambda that returns null on some paths only is not reported — that is ordinary conditional
logic, not the "always null" shape this rule targets — and neither is a method reference
argument, whose body is not visible to the rule.