Hello there,
Both code snippets violate the bug rule RSPEC-1226, however, when scanned with Sonarqube 10.7 the bug is not consistently flagged in both code snippets.
code snippet 1:
import java.util.HashMap;
import java.util.Map;
class MapComputeBug {
public Map<String, String> showBug(String key) {
Map<String, String> map = new HashMap<>();
map.computeIfAbsent(key, k -> null);
return map;
}
public static void main(String[] args) {
MapComputeBug bug = new MapComputeBug();
Map<String, String> result = bug.showBug("key");
System.out.println(result);
}
}
code snippet 2:
import java.util.Random;
class MapComputeBug {
public Map<String, String> showBug(String key) {
Map<String, String> map = new HashMap<>();
map.computeIfAbsent(key, k -> null);
String randomVar = generateRandomString();
return map;
}
private String generateRandomString() {
int leftLimit = 97; // letter 'a'
int rightLimit = 122; // letter 'z'
int targetStringLength = 8;
Random random = new Random();
StringBuilder buffer = new StringBuilder(targetStringLength);
for (int i = 0; i < targetStringLength; i++) {
int randomLimitedInt = leftLimit + (int)(random.nextFloat() * (rightLimit - leftLimit + 1));
buffer.append((char) randomLimitedInt);
}
return buffer.toString();
}
public static void main(String[] args) {
MapComputeBug bug = new MapComputeBug();
Map<String, String> result = bug.showBug("key");
System.out.println(result);
}
}
Scanning information:
Sonarqube version: 10.7.0.96327
SonarScanner version: 5.0.1.3006
SonarQube Community Edition
Related language: Java
Thanks for your time and consideration.