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

Empty arrays and collections should be returned instead of null

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Return an empty [array|collection] instead of null.
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Targeted languages:
      C, C++, Flex, Objective-C
    • Covered Languages:
      C#, Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      30min
    • Analysis Scope:
      Main Sources
    • CERT:
      MSC19-C., MET55-J.
    • FindBugs:
      PZLA_PREFER_ZERO_LENGTH_ARRAYS
    • PMD:
      ReturnEmptyArrayRatherThanNull

      Description

      Returning null instead of an actual array or collection forces callers of the method to explicitly test for nullity, making them more complex and less readable.
      Moreover, in many cases, null is used as a synonym for empty.

      Noncompliant Code Example

      public static List<Result> getResults() {
        return null;                             // Noncompliant
      }
      
      public static Result[] getResults() {
        return null;                             // Noncompliant
      }
      
      public static void main(String[] args) {
        Result[] results = getResults();
        
        if (results != null) {                   // Nullity test required to prevent NPE
          for (Result result: results) {
            /* ... */
          }
        }
      }
      

      Compliant Solution

      public static List<Result> getResults() {
        return Collections.emptyList();          // Compliant
      }
      
      public static Result[] getResults() {
        return new Result[0];
      }
      
      public static void main(String[] args) {
        for (Result result: getResults()) {
          /* ... */
        }
      }
      

      See

      • CERT, MSC19-C. - For functions that return an array, prefer returning an empty array over a null value
      • CERT, MET55-J. - Return an empty array or collection instead of a null value for methods that return an array or collection

        Attachments

          Issue Links

          1.
          C# RSPEC-4171 Language-Specification Active Unassigned

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              freddy.mallet Freddy Mallet (Inactive)
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: