Wednesday, July 8, 2009

Groovy Class for Analyzing java code

A lot of times when i sit down to review code, there are some basic things like the size of the class, the total lines, the maximum width of a line etc, which can help in figuring out bad smells in code. In order to automate the task i wrote a small groovy class which can be run on a directory to figure out these metrices. Although there are lots of tools available, the simplicity and the customization which can be done to a small utility class far outweigh the advantages.

class CodeAnalyzer {
int lineCount
int maxLineWidth
int widestLineNumber
int totalChars
int lineSize
def List findJavaFiles(File parentDir){
def files=new ArrayList()
parentDir.eachFileRecurse{file ->
if(file.isFile() && file.name.endsWith(".java"))
files.add(file)
}
return files
}
def analyzeFile(File javaFile){
javaFile.eachLine{line ->
measureLine(line)
}
println "fileName =" + javaFile.name
println "lineCount =" + lineCount
println "maxLineWidth ="+maxLineWidth
println "widestLineNumber ="+widestLineNumber
println "totalChars ="+totalChars
}
def measureLine(String line){
lineCount++
lineSize=line.length()
totalChars +=lineSize
recordWidestLine(lineSize)
}
def recordWidestLine(int lineSize){
if(lineSize >maxLineWidth){
maxLineWidth =lineSize
widestLineNumber=lineCount
}
}
def getMeanLineWidth(){
return totalChars/lineCount
}
}
The semantics of usage are pretty simple. I will show the groovy way of invoking it
CodeAnalyzer codeAnalyzer=new CodeAnalyzer()
codeAnalyzer.findJavaFiles(new File("D:/MCubeRTV2.0/Source/java/com/velozglobal/mcube/agents")).each{file ->
codeAnalyzer.analyzeFile(file)
}


The emperor and me beaching

The Devil next door

Kaiser The Emperor