Reputation: 7683
My method below needs to return a String concatenated from strings.
StringBuilder sb = new StringBuilder();
sb.append("count: ").append(this.count()).append( "\n");
return sb.toString();
In IntelliJ, the Code Inspection suggests me to replace this StringBuilder with a String like below:
String sb = "count: " + this.count() + "\n";
return sb
My impression is that StringBuilder should be used with the append method, to replace string concatenation with the plus sign. Does this code inspection suggestion make sense in IntelliJ?
Upvotes: 6
Views: 4368
Reputation: 40408
You are correct in your presumptions that most IntelliJ inspections encourage you to do things in a "better" way.
However, this is not always the case. Especially where some inspections work "both ways" -> you'll have to exercise your own judgement about what is "better".
In this case, if you start with a normal concatenated string:
return "count: " + count + "\n";
There are a few inspections available - put cursor on "count: "
and hit alt-enter:
If you choose option (2), you get this:
return new StringBuilder().append("count: ").append(count).append("\n").toString();
Now, you can use alt-enter again to choose "Replace StringBuilder with String" reverse the change.
In this case, you have discovered an inspection / refactoring that is bi-directional: it works both ways. Other refactorings (such as "Encapsulate") work only one way.
As for what is "better" - you have to weigh up the performance of StringBuilder
versus readability and simplicity, and make that judgement yourself - IntelliJ is just providing handy inspections to assist you ;)
Upvotes: 7