2

基于这个问题,CheckStyle 的默认模板似乎将允许 if else 梯子用换行符分隔ifand 。else

这意味着我希望将此代码标记为违规:

if (true)
{
    System.out.println("20");   
}
else
    if (true)
    {
        System.out.println("30");
    }

是否有 CheckStyle 规则来防止这种情况?查看文档,我没有看到一个,如果我不需要的话,我不想使用通用的正则表达式规则。

此外,如果我使用GenericIllegalRegexp模块,多行正则表达式似乎不起作用。有什么补救措施吗?

4

1 回答 1

2

我不确定您是否可以轻松编写 Checkstyle 扩展,因为Checkstyle SDK Gui的 AST 浏览代码在以下方面没有任何区别:

else if

else
  if

在每种情况下,else是一个LITERAL_ELSE在其中if...

所以通用正则表达式else[ \t]*[\r\n]+[ \t]*if确实是检测这种代码的一种快速方法。


修复正则表达式以包括案例:

  • 在换行符之前/之后没有空格而不是制表符
  • 这是多个换行符。

当然,您不想使用\s空格正则表达式,因为它本身包含换行符。将空格与返回字符分开会更清楚。


Note: in Checkstyle 5.0beta, do not use "Generic Illegal Regexp", but rather the "Regexp" module:
you can configure that RegExp module as 'illegalPattern' (with an associated Severity of 'Warning'), and you do not have to use any kind af 'multi-line' flag: the regexp is enough.

Regexp
Description

A check that makes sure that a specified pattern exists, exists less than a set number of times, or does not exist in the file.

This check combines all the functionality provided by RegexpHeader, GenericIllegalRegexp and RequiredRegexp, except supplying the regular expression from a file.

It differs from them in that it works in multiline mode. It's regular expression can span multiple lines and it checks this against the whole file at once. The others work in singleline mode. Their single or multiple regular expressions can only span one line. They check each of these against each line in the file in turn.


Thomas mentions in the comments:

The checkstyle AST does have line number information.

See "Is there any Checkstyle/PMD/Findbugs rule to force “<code>else if” to be on the same line?"
(in which one has to use a custom check, and not a regex match).

于 2008-12-22T22:13:28.287 回答