Search code examples
javaxpathstatic-analysispmd

PMD - check for too many public methods (but exclude constructors and getters/setters)


I wish to add a PMD check to ensure that a class does not have too many public methods, but I do not want constructors and getters/setters to be included in the check.

The ExcessivePublicCount check includes constructors, getters/setters and public variables, and I can't see a way to customise it.

The TooManyMethods check excludes getters/setters, but includes everything else (including private methods). The XPath code for the check is as follows.

//ClassOrInterfaceDeclaration/ClassOrInterfaceBody
[
    count(descendant::MethodDeclarator[
        not
        (
        starts-with(@Image,'get')
            or
        starts-with(@Image,'set')
        )
    ]) > $maxmethods
]

Can anyone help me out with modifying this to achieve what I want, or suggest another way to do this with PMD?


Solution

  • //ClassOrInterfaceDeclaration/ClassOrInterfaceBody [
     count(descendant::MethodDeclarator[
     ..[@Public='true']
      and
     not
     (
      starts-with(@Image,'get')
       or
      starts-with(@Image,'set')
       or
      starts-with(@Image,'is')
     )
     ] ) > $maxmethods
    ]
    

    You are counting MethodDeclarator so ctors should not be included.
    ..[@Public='true']
    Go back one from the MethodDeclarator to the MethodDeclaration, and then check if it is public.