Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all naive ("+" based) string concatenations in large Java codebase?

We have a huge code base and we suspect that there are quite a few "+" based string concats in the code that might benefit from the use of StringBuilder/StringBuffer. Is there an effective way or existing tools to search for these, especially in Eclipse?

A search by "+" isn't a good idea since there's a lot of math in the code, so this needs to be something that actually analyzes the code and types to figure out which additions involve strings.

like image 874
Uri Avatar asked Jun 16 '09 20:06

Uri


2 Answers

I'm pretty sure FindBugs can detect these. If not, it's still extremely useful to have around.

Edit: It can indeed find concatenations in a loop, which is the only time it really makes a difference.

like image 187
Michael Myers Avatar answered Oct 13 '22 09:10

Michael Myers


Just make sure you really understand where it's actually better to use StringBuilder. I'm not saying you don't know, but there are certainly plenty of people who would take code like this:

String foo = "Your age is: " + getAge();

and turn it into:

StringBuilder builder = new StringBuilder("Your age is: ");
builder.append(getAge());
String foo = builder.toString();

which is just a less readable version of the same thing. Often the naive solution is the best solution. Likewise some people worry about:

String x = "long line" + 
    "another long line";

when actually that concatenation is performed at compile-time.

As nsander's quite rightly said, find out if you've got a problem first...

like image 41
Jon Skeet Avatar answered Oct 13 '22 09:10

Jon Skeet