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

"null" should not be used with "Optional"

    XMLWordPrintable

    Details

    • Type: Bug Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Hide
      * Remove this null-check of an "Optional".
      * Methods with an "Optional" return type should never return null.
      * Methods with an "Optional" return type should not be "@Nullable".
      * "Optional" variables should not be "@Nullable".
      Show
      * Remove this null-check of an "Optional". * Methods with an "Optional" return type should never return null. * Methods with an "Optional" return type should not be "@Nullable". * "Optional" variables should not be "@Nullable".
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      15min
    • Analysis Scope:
      Main Sources, Test Sources
    • FindBugs:
      NP_OPTIONAL_RETURN_NULL

      Description

      The concept of Optional is that it will be used when null could cause errors. In a way, it replaces null, and when Optional is in use, there should never be a question of returning or receiving null from a call.

      Noncompliant Code Example

      public void doSomething () {
        Optional<String> optional = getOptional();
        if (optional != null) {  // Noncompliant
          // do something with optional...
        } 
        Optional<String> text = null; // Noncompliant, a variable whose type is Optional should never itself be null
        // ...
      }
      
      @Nullable // Noncompliant
      public Optional<String> getOptional() {
        // ...
        return null;  // Noncompliant
      }
      

      Compliant Solution

      public void doSomething () {
        Optional<String> optional = getOptional();
        optional.ifPresent(
          // do something with optional...
        );
        Optional<String> text = Optional.empty();
        // ... 
      }
      
      public Optional<String> getOptional() {
        // ...
        return Optional.empty();
      }
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              ann.campbell.2 Ann Campbell
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: