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

Collection sizes and array length comparisons should make sense

    XMLWordPrintable

    Details

    • Type: Bug Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
      None
    • Message:
      The [size|length] of ["XXX"|an array|a collection] is always ">=0", so update this test to [either "==0" or ">0"|use "isEmpty()"].
    • Highlighting:
      Hide

      The boolean expression with the ">=" or "<" operator and the two operands

      Show
      The boolean expression with the ">=" or "<" operator and the two operands
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Targeted languages:
      APEX, Flex, Kotlin, Objective-C, PL/SQL, Ruby, Rust, Scala, Solidity, T-SQL, VB6
    • Covered Languages:
      C#, Go, Java, JavaScript, PHP, Python, Swift, TypeScript, VB.Net
    • Irrelevant for Languages:
      ABAP, C, C++, Cobol, CSS, HTML, PL/I, RPG, XML
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      2min
    • Analysis Level:
      Syntactic Analysis
    • Analysis Scope:
      Main Sources, Test Sources
    • Common Rule:
      Yes
    • TSLint-SonarTS:
      no-collection-size-mischeck

      Description

      The size of a collection and the length of an array are always greater than or equal to zero. So testing that a size or length is greater than or equal to zero doesn't make sense, since the result is always true. Similarly testing that it is less than zero will always return false. Perhaps the intent was to check the non-emptiness of the collection or array instead.

      Noncompliant Code Example

      if (myList.size() >= 0) { ... }
      
      if (myList.size() < 0) { ... }
      
      boolean result = myArray.length >= 0;
      
      if (0 > myArray.length) { ... }
      

      Compliant Solution

      if (!myList.isEmpty()) { ... }
      
      if (myArray.length >= 42) { ... }
      

        Attachments

          Issue Links

            Activity

              People

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

                Dates

                Created:
                Updated: