Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-3824

"Map.get" and value test should be replaced with single method call

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Replace this ("Map.get()" and condition | "Map.containsKey()") with a call to ("Map.computeIfAbsent()" | "Map.computeIfPresent()").
    • Highlighting:
      Hide

      Primary: condition
      Secondary: Map.get call or Map.containsKey call

      Show
      Primary: condition Secondary: Map.get call or  Map.containsKey  call
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      10min
    • Analysis Scope:
      Main Sources, Test Sources

      Description

      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

      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

      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.

      See also

      • S6104 - Map "computeIfAbsent()" and "computeIfPresent()" should not be used to add "null" values.

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              jeanchristophe.collet Jean-Christophe Collet (Inactive)
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: