Tool to identify cohesive blocks of (JAVA) code

952 Views Asked by At

I am wondering if there is a tool that can identify cohesive blocks of code within JAVA source code. For example if I had a long method that I would like to extract another method from - is there any tool that automatically can tell me large chunks of code that would be worth extracting?

5

There are 5 best solutions below

0
On

Control blocks (i.e. conditionals and loops) are "cohesive" in that you cannot readily extract blocks of code that cross control block boundaries. Find blocks that can be replaced by a method call, that makes the original method easier to understand. You will have the best impact on complexity by extracting out the regions of deepest control flow nesting, so this is a good place to start. You don't need a tool as such - the code itself has the info you need.

0
On

I looked for a similar tool with another question: https://stackoverflow.com/questions/12016289/tool-for-visualizing-dependencies-inside-a-java-class just on a slightly higher level: a single class.

I think the same answer applies: There isn't anything like that. There are tools though that provide information from which you might extract the information you are looking for.

I'd look into DependencyFinder. It provides access to all the bits and pieces of the code, so you could find clusters of code elements that access a common set of variables. Unfortunately I found the API a little confusing and not well documented, so you'll need some try and error or get into contact with the author. It also probably won't give you access to whitespace I think. But I don't think this is a valid approach anyway.

Another Tool you might want to look into is JaMoPP It should even have information about whitespace. Although it is a Java Plugin you can use the underlying library independent of eclipse (I think).

1
On

There are plug-ins like PMD (for eclipse) & FindBugs etc., to do static code review which flags code based on rules your configured.

1
On

Check out Sonar It has very good support for finding duplicate code blocks.

Sonar uses PMD and FindBugs underlying. It also generates some custom metrics like class complexity, method complexity which points to classes / methods that are too large and which are candidate for breaking down.

0
On

Google CodePro Analytics has an Eclipse plug-in that can provide a bunch of statistics like lines of code and cyclomatic complexity that can be good indicators that a method should be refactored.

I don't think you will find a tool that can automatically refactor 'cohesive' blocks of code into methods. There is too much subjectivity in that.