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

Collection.isEmpty() should be used to test for emptiness

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Use isEmpty() to check whether the collection is empty or not.
    • Default Severity:
      Minor
    • Impact:
      Low
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Targeted languages:
      Go, Python, Swift
    • Covered Languages:
      C#, C++, Java, PHP
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      2min
    • Analysis Level:
      Semantic Analysis
    • Analysis Scope:
      Main Sources, Test Sources
    • Common Rule:
      Yes
    • CppCoreGuidelines:
      T.143
    • FxCop:
      CA1827
    • PMD:
      UseCollectionIsEmpty
    • SwiftLint:
      empty_count

      Description

      Using Collection.size() to test for emptiness works, but using Collection.isEmpty() makes the code more readable and can be more performant. The time complexity of any isEmpty() method implementation should be O(1) whereas some implementations of size() can be O.

      Noncompliant Code Example

      if (myCollection.size() == 0) {  // Noncompliant
        /* ... */
      }
      

      Compliant Solution

      if (myCollection.isEmpty()) {
        /* ... */
      }
      

        Attachments

          Issue Links

            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: