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

Ternary operators should not be nested

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Extract this nested ternary operation into an independent statement.
    • Highlighting:
      Hide

      Primary: highlight the entire nested ternary operation

      Show
      Primary: highlight the entire nested ternary operation
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Targeted languages:
      ABAP, APEX, Flex, PL/SQL, Rust, Scala, T-SQL, TypeScript
    • Covered Languages:
      C#, C, C++, Java, JavaScript, Objective-C, PHP, Python, Swift, VB.Net
    • Irrelevant for Languages:
      Cobol, Go, HTML, Kotlin, PL/I, RPG, Ruby, VB6, XML
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      5min
    • Analysis Level:
      Syntactic Analysis
    • Analysis Scope:
      Main Sources, Test Sources
    • Common Rule:
      Yes
    • ESLint:
      no-nested-ternary

      Description

      Just because you can do something, doesn't mean you should, and that's the case with nested ternary operations. Nesting ternary operators results in the kind of code that may seem clear as day when you write it, but six months later will leave maintainers (or worse - future you) scratching their heads and cursing.

      Instead, err on the side of clarity, and use another line to express the nested operation as a separate statement.

      Noncompliant Code Example

      public String getReadableStatus(Job j) {
        return j.isRunning() ? "Running" : j.hasErrors() ? "Failed" : "Succeeded";  // Noncompliant
      }
      

      Compliant Solution

      public String getReadableStatus(Job j) {
        if (j.isRunning()) {
          return "Running";
        }
        return j.hasErrors() ? "Failed" : "Succeeded";
      }
      

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                nicolas.peru Nicolas Peru
              • Votes:
                2 Vote for this issue
                Watchers:
                2 Start watching this issue

                Dates

                • Created:
                  Updated: