dea*_*nix 12 java if-statement checkstyle
我使用checkstyle来检查我的java代码是否符合我们项目的指导原则.
但是,我们有一个指南,我无法弄清楚如何使用此工具进行检查.我们想要允许简单的if(理解是否没有其他,没有其他条件结构)没有大括号,就像在这个例子中:
// valid
if(condition) callFunction();
// invalid
if(condition) for(int i = 0; i < someValue; i++) callFunction(i);
// valid
if(condition) {
for(int i = 0; i < someValue; i++) {
callFunction(i);
}
}
// invalid
if(condition) callFunction();
else callOtherFunction();
Run Code Online (Sandbox Code Playgroud)
可以讨论这个约定,但这是我们选择的.它允许减少非常琐碎的if语法,但确保我们对更复杂的结构有良好的缩进和块定界.
任何帮助都将非常感激.
我还准备做一些代码来执行此检查,如果没有可用的,但实际上不知道从哪里开始.在最后一次报道中,关于这一点的一些提示也将受到赞赏.
最后,我确实为checkstyle实现了自定义检查.以下是其他人对此感兴趣的源代码:
import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
public class IfBracesCheck extends Check {
@Override
public int[] getDefaultTokens() {
return new int[] {
TokenTypes.LITERAL_ELSE,
TokenTypes.LITERAL_IF,
};
}
@Override
public void visitToken(DetailAST aAST) {
final DetailAST slistAST = aAST.findFirstToken(TokenTypes.SLIST);
if(aAST.getType() == TokenTypes.LITERAL_ELSE) {
// If we have an else, it must have braces, except it is an "else if" (then the if must have braces).
DetailAST ifToken = aAST.findFirstToken(TokenTypes.LITERAL_IF);
if(ifToken == null) {
// This is an simple else, it must have brace.
if(slistAST == null) {
log(aAST.getLineNo(), "ifBracesElse", aAST.getText());
}
} else {
// This is an "else if", the if must have braces.
if(ifToken.findFirstToken(TokenTypes.SLIST) == null) {
log(aAST.getLineNo(), "ifBracesConditional", ifToken.getText(), aAST.getText() + " " + ifToken.getText());
}
}
} else if(aAST.getType() == TokenTypes.LITERAL_IF) {
// If the if uses braces, nothing as to be checked.
if (slistAST != null) {
return;
}
// We have an if, we need to check if it has no conditionnal structure as direct child.
final int[] conditionals = {
TokenTypes.LITERAL_DO,
TokenTypes.LITERAL_ELSE,
TokenTypes.LITERAL_FOR,
TokenTypes.LITERAL_IF,
TokenTypes.LITERAL_WHILE,
TokenTypes.LITERAL_SWITCH,
};
for(int conditional : conditionals) {
DetailAST conditionalAST = aAST.findFirstToken(conditional);
if (conditionalAST != null) {
log(aAST.getLineNo(), "ifBracesConditional", aAST.getText(), conditionalAST.getText());
// Let's trigger this only once.
return;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)