Java Checkstyle Rule To Restrict Method Empty Lines

与世无争的帅哥 提交于 2020-05-09 05:22:01

问题


Is there a way to setup checkstyle to prevent leading, multiple or trailing empty lines in method bodies:

e.g.

private void a() {
-
int a = 1;
doStuff(a);
-
-
doMoreStuff(a);
-
}

In the example above, I have denoted empty lines with - characters.

I'd like to be able to to prevent the leading line, trailing line and more than one line in the method body.


回答1:


To enforce no blank lines at the beginning and end of any block, you can use multi-line regular expression checks:

<module name="RegexpMultiline">
    <property name="message" value="Blank line at start of block should be removed" />
    <property name="format" value="(?&lt;=\{\s{0,99}$)^$" />
    <property name="fileExtensions" value="groovy,java" />
</module>
<module name="RegexpMultiline">
    <property name="message" value="Blank line at end of block should be removed" />
    <property name="format" value="(?&lt;!\{\s{0,99}$)^$(?=^\s{0,99}\})" />
    <property name="fileExtensions" value="groovy,java" />
</module>

"^$" signifies the blank line.




回答2:


To prevent leading empty lines in method bodies, you can use:

<module name="RegexpMultiline">
    <property name="message" value="Blank line at start of method should be removed"/>
    <property name="format" value="\(.*\)\s*\{\s*\n\s*\n"/>
</module>

We can find method by parentheses.




回答3:


To prevent multiple empty lines you can use the EmptyLineSeparator check. Its primary purpose is to ensure that there is an empty line between members in a file, but it also has a allowMultipleEmptyLines property which you can set to "false" to disallow them.

There is however currently a bug with the check that means it doesn't correctly detect multiple empty lines between methods where there is a comment (including JavaDoc) between the methods. I am working on a fix for this at the moment.

As for checking for new lines at the beginning or end of a block, I think the RegexpMultiline check would be the only option as mentioned in Pankaj's answer.




回答4:


Can use it:

<module name="Regexp">
    <property name="message" value="Blank line at start of block is not allowed"/>
    <property name="format" value="\{\s*$^\s*$"/>
    <property name="ignoreComments" value="true"/>
    <property name="illegalPattern" value="true"/>
</module>
<module name="Regexp">
    <property name="message" value="Blank line at end of block is not allowed"/>
    <property name="format" value="^\s*$^\s*\}"/>
    <property name="ignoreComments" value="true"/>
    <property name="illegalPattern" value="true"/>
</module>


来源:https://stackoverflow.com/questions/48027686/java-checkstyle-rule-to-restrict-method-empty-lines

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