Is there a CheckStyle rule to force if else keywords to be on the same line in an if/else ladder?

只谈情不闲聊 提交于 2019-12-20 03:43:13

问题


Based on this question it appears that the default template for CheckStyle will allow if else ladders to separate the if and else with a line break.

Meaning I would like this code to be flagged as a violation:

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

Is there a CheckStyle rule to prevent this? Looking over the docs, I don't see one, and I'd prefer not to use the generic regex rule, if I don't have to.

Also, if I use the GenericIllegalRegexp module, multiline regex don't seem to work. Is there some remedy to this?


回答1:


I am not sure you can easily write a Checkstyle extension, since the AST browsing code of the Checkstyle SDK Gui does not make any difference between:

else if

and

else
  if

In each case, else is a LITERAL_ELSE with in it an if...

So the generic regexp else[ \t]*[\r\n]+[ \t]*if is indeed a quick way to detect that kind of code.


Fix the regexp to include cases were :

  • there is no space not tab before/after newline
  • the is multiple newlines.

Of course, you do not want to use the \s whitespace regexp expression, since it includes itself newline characters. It is clearer to separate spaces from return characters.


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 “else if” to be on the same line?"
(in which one has to use a custom check, and not a regex match).



来源:https://stackoverflow.com/questions/387008/is-there-a-checkstyle-rule-to-force-if-else-keywords-to-be-on-the-same-line-in-a

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