5

I want to tune the TooManyFields PMD rule so it doesn't count my injected services as field. Is there a way to do it in the pmd xml file like by using violationSuppressXPath even if it's a java class ? Or does violationSuppressXPath only work to avoid the rule being applied at all ?

I would like to identify the Spring services by either the annotation @WireVariable or by the name (ending by 'service').

TheBakker
  • 2,852
  • 2
  • 28
  • 49
  • 1
    This solution (ignoring annotated methods) might help: http://stackoverflow.com/a/34919039/4014509. I am a PMD ruleset noob, but I am sure it is no problem to create a similar XPath expression for fields. – Sebastian S Sep 16 '16 at 22:00

3 Answers3

4

Having the field as Spring injected service doesn't make it less of a field, so it is still not a good practice to have too many fields. Developer adding new functionality to the class will have to deal with all those fields.

You can suppress the warning only per class, like this:

@SuppressWarnings("PMD.TooManyFields")
public class Foo {
...
}
Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115
0

add below rule

 <rule ref="category/java/design.xml" >
   <exclude name="TooManyFields" />
 </rule>
  • 1
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – Dwhitz Apr 09 '19 at 10:25
  • Sorry but this remove the TooManyFields rule as a whole. My question was about being able to remove injected service from the rule count, which is not an available option atm. – TheBakker Apr 11 '19 at 10:43
0

First: that rule is total nonsense. The count of fields is driven by the entities and objects you are modelling, so disrupting designs and distribute stuff into different classes often lowers clarity.

For the service stuff, there is an usable approch: Use inheritance and put all services into the base class, e.g.

public class Services4Xyz {
    @Inject
    protected Something something;
...
}

public class Xyz extends Services4Xyz {
    private String myText;

    void foo() {
        something.doSomething(myText);
    }
}

Anoother approach is, to group attributes into an object. With services that needs to be a bean:

// provided as a bean
public class Services4Xyz {
    @Inject
    protected Something something;

    public Something getSomething() {
        return something;
    }
...
}

public class Xyz {
    @Inject
    private Services4Xyz services4Xyz;

    private String myText;

    void foo() {
        services4Xyz.getSomething().doSomething(myText);
    }
}
bebbo
  • 2,830
  • 1
  • 32
  • 37