且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否有任何Checkstyle / PMD / Findbugs规则强制“ else if”在同一条线上?

更新时间:2022-10-22 20:47:31

可以使用CheckStyle完成,但您必须 $ t {] * [\r\n] + [\t {] * if\b 用于 format 属性(基于这篇文章)。


以下是上述正则表达式作为铁路图:


事实证明不是可行,因为当 else if 之间存在注释时,它会产生假阴性。更糟糕的是,当嵌套的 if 后跟无关的代码(例如 else {if(){...}< block }} 。感谢@Anatoliy指出!由于正则表达式不能可靠地把握注释以及与注释混合的括号,因此这些问题使RegExp方法过时了。


In our project for chained if/else/if we would like to have following formatting:

if (flag1) {
    // Do something 1
} else if (flag2) {
    // Do something 2
} else if (flag3) {
    // Do something 3
}

And forbid following one:

if (flag1) {
    // Do something 1
} else {
    if (flag2) {
        // Do something 2
    } else {
        if (flag3) {
            // Do something 3
        }
    }
}

Is there some predefined rule in either of listed above static code analysis tools to force this code style? If no - I know there is an ability to write custom rules in all of those tools, which one would you suggest to implement such a rule (not really familiar with writing custom rules in either of them)?

It can be done with CheckStyle, but you'll have to code a custom check.

Using a custom check allows you to completely ignore comments. The line number that a token is on can be determined by calling getLineNo() on the DetailAST. Here's what the AST looks like, with line number information (red circles):

The custom check's code will likely be quite short. You basically register for LITERAL_ELSE tokens and see if LITERAL_IF is their only child. Also remember to handle SLISTs. In those cases, LITERAL_IF and RCURLY should be the only children. Both cases are illustrated in the above picture.


Alternative using a RegExp check

For the record, I originally thought one could also configure a regex match using else[ \t{]*[\r\n]+[ \t{]*if\b for the format property (based on this post).

Here's the mentioned regex as a railroad diagram:

This turned out not to be feasible, because it produces false negatives when there are comments between between else and if. Worse, it also produces false positives when the nested if is followed by unrelated code (like else { if() {...} <block of code>}. Thanks @Anatoliy for pointing this out! Since comments and matching braces which are mixed with comments cannot be reliably grasped by regexes, these problems obsolete the RegExp approach.