是否有任何Checkstyle / PMD / Findbugs规则强制“ else if”在同一条线上? [英] Is there any Checkstyle/PMD/Findbugs rule to force "else if" to be on the same line?

查看:62
本文介绍了是否有任何Checkstyle / PMD / Findbugs规则强制“ else if”在同一条线上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的链式if / else / if项目中,我们希望采用以下格式:

  if(flag1){ 
//做某事1
}否则,如果(flag2){
//做某事2
}否则,如果(flag3){
//做某事3
}

并禁止以下行为:

  if(flag1){
//做某事1
} else {
if(flag2){
//做某事2
} else {
if(flag3){
//做某事3
}
}
}

上面列出的任一静态代码分析工具中是否都存在一些预定义的规则来强制使用此代码样式?如果没有-我知道所有这些工具都可以编写自定义规则,那么您会建议实施哪一种规则(对这两个工具都不习惯编写自定义规则)?

解决方案

可以使用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.

这篇关于是否有任何Checkstyle / PMD / Findbugs规则强制“ else if”在同一条线上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆