Ensure that fields with specific annotations are 'private'

自作多情 提交于 2019-12-11 11:53:42

问题


Very common mistake in our code is to write

@Mock Object object;
@InjectMocks Subject subject;

instead of

@Mock private Object object;
@InjectMocks private Subject subject;

This prevents PMD/FindBugs/IntelliJ from issuing warning when the field becomes unused and also our code reviews are bloated with "make this field private" comments.

Is there any static-analysis rule in any tool to warn when fields with specific annotations do not have expected visibility?

I found Checkstyle's VisibilityModifier, but it marks all non-private fields, not just the ones with specific annotations.


回答1:


You could use the Structural Search Inspection in IntelliJ IDEA. For example with a pattern like this:

@Mock @Modifier("packageLocal") $FieldType$ $FieldName$ = $Init$;

FieldType: min: 1, max: 1
FieldName: min: 1, max: 1
Init: min: 0, max: 1




回答2:


You could use PMD's Rule Designer to create a new XPath rule, which can be embedded into a PMD ruleset xml file. I haven't used PMD with IntelliJ IDEA or Jenkins, but I'm sure the plugins exist.

Here's a rule I've made (not tested outside the Rule Designer):

<rule  name="NonPrivateMockAnnotation"
  message="Mock anotation should be private"
  class="net.sourceforge.pmd.lang.rule.XPathRule">
  <description>
  </description>
  <properties>
    <property name="xpath">
    <value>
<![CDATA[
//ClassOrInterfaceBodyDeclaration[
    Annotation/MarkerAnnotation/Name[
        @Image = 'InjectMocks' or
        @Image = 'Mock' 
    ] and
    FieldDeclaration/@Private = 'false'
]
]]>
    </value>
    </property>
  </properties>
  <priority>3</priority>
  <example>
<![CDATA[
class Example {
  @Mock Object object;
  @InjectMocks Subject subject;
}
]]>
  </example>
</rule>


来源:https://stackoverflow.com/questions/33660204/ensure-that-fields-with-specific-annotations-are-private

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!