Uploaded image for project: 'SonarJava'
  1. SonarJava
  2. SONARJAVA-3157

FP on Rule S2637 - issue raised on non-initialized fields

    Details

    • Type: False-Positive
    • Status: Open
    • Priority: Major
    • Resolution: Unresolved
    • Affects Version/s: None
    • Fix Version/s: 6.2
    • Component/s: Rules, Symbolic Execution
    • Labels:
      None

      Description

      Annotations in javax.validation.constraints.* such as @NotNull are used for validation. It is perfectly normal for a Java Bean to have null fields until they are set for the first time, which can happen after the object is instantiated.

      A good example of how @NotNull is used is visible in Spring documentation when it handles forms.

      public class PersonForm {
      
          @NotNull
          private String name;
      
          public String getName() {
              return this.name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      }
      
      @Controller
      public class WebController implements WebMvcConfigurer {
      
          @PostMapping("/")
          public String checkPersonInfo(@Valid PersonForm personForm, BindingResult bindingResult) {
              // ...
          }
      }
      

      Currently the rule RSPEC-2637 raises an issue when a class constructor is not initalizing an attribute annotated with @NotNull, which is a valid use case. We should remove this False positive.

      Compliant Code:

      public class PersonForm {
      
          @NotNull
          private String name;
      
          public PersonForm() {} // Constructor does not initalize "name"
      
          public String getName() {
              return this.name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      }
      

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                nicolas.harraudeau Nicolas Harraudeau
              • Votes:
                0 Vote for this issue
                Watchers:
                1 Start watching this issue

                Dates

                • Created:
                  Updated: