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

S1258 FP in the Builder pattern and maven annotated classes

    Details

    • Type: False-Positive
    • Status: Closed
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 5.14
    • Component/s: Rules
    • Labels:
      None

      Description

      public class FooBuilder { // Fp raised because of missing appropriate constructor.
      
           private String someProperty;
           private String otherProperty;
      
           public Foo build() {
               if (someProperty == null || otherProperty == null) {
                   throw new IllegalStateException("Builder is missing some data.");
               } else {
                   return new Foo(someProperty, otherProperty);
               }
           }
      
           public FooBuilder withSomeProperty(String p) {
               this.someProperty = p;
               return this;
           }
       
           public FooBuilder withOtherProperty(String p) {
               this.otherProperty = p;
               return this;
           }
      
      } 

      The best approach to solve this false positive is to rely on the heuristic that any class named "*Builder" will most probably implement a builder pattern and as such should not raise an issue for this rule. Let's kill the noise.

       

      Another case to support is when classes are used in maven mojo development : 

      import org.apache.maven.plugins.annotations.Component;
      import org.apache.maven.plugins.annotations.Mojo;
      import org.apache.maven.plugins.annotations.Parameter;
      
      @Mojo(name = "myMojo")
      public class MyMojo extends AbstractMojo {
         
          @Parameter(property = "project", readonly = true, required = true)
          private MavenProject project;
      
          @Component
          private ProjectDependenciesResolver resolver;
      
          @Parameter(property = "my.skip", defaultValue = "false")
          private boolean skip;
      } 

      Or 

      import org.codehaus.plexus.component.annotations.Component;
      import org.codehaus.plexus.component.annotations.Requirement;
      
      @Component( role = MyComponent.class, hint = "hint-value" )
      public class MyComponentImplementation implements MyComponent {
      
          @Requirement
          private InjectedComponent;
      } 

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                quentin.jaquier Quentin Jaquier
                Reporter:
                nicolas.peru Nicolas Peru
              • Votes:
                0 Vote for this issue
                Watchers:
                3 Start watching this issue

                Dates

                • Due:
                  Created:
                  Updated:
                  Resolved: