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)
}

Advertisements

One Response to Groovy Class for Analyzing java code

  1. Anuj Mehta says:

    Hey Maneesh

    Nice blog. I really like your article about JVM internals on DZone…waiting for next part

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: