Tuesday, November 24, 2009

Customize Checkstyle

Checkstyle is one of java code review tool and is highly configurable.
One of the customized check is given below.
Check to find the usage of "+=" for String concatenation.
Below code checks for the usage of "+=" for String concatenation in the java file and reports the same.This is one of the most useful check which does not come with checkstyle_checks.xml.
Lets name the check as "StringConcatenationCheck".

import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
public class StringConcatenationCheck extends Check{
/** Creates a new instance of StringConcatenationCheck */
public StringConcatenationCheck() { }
public int[] getDefaultTokens(){
return new int[]{
TokenTypes.PLUS_ASSIGN
}; }
public void visitToken(DetailAST plusAssignNode){
if(plusAssignNode.branchContains(TokenTypes.STRING_LITERAL))
log(plusAssignNode.getLineNo(),"stringusage.err.msg");
}}

Just add the name of the check in your checkstyle_checks.xml to use it.

Similarly we can write checks to check if database connections/streams are properly closed.
Let me know if anybody insterested in source code.

No comments: