Is there a CheckStyle rule to force if else keywor

2019-02-26 04:08发布

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条回答
在下西门庆
2楼-- · 2019-02-26 04:35

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).

查看更多
登录 后发表回答