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?
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:
and
In each case,
else
is aLITERAL_ELSE
with in it anif
...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 :
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.
Thomas mentions in the comments:
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).