Reputation: 448
I'm currentlly refactoring an application using a lot of this:
StringBuffer buff1 = new StringBuffer("");
buff1.append("some value A");
buff1.append("");
buff1.append("some value B");
The coder that made those code lines didn't seems to be an idiot, is there any reasons I can't see to use the append("") to a StringBuffer?
Upvotes: 3
Views: 4448
Reputation: 187499
If there are no further appends made to the StringBuffer the code should be rewritten as
String buff1 = "some value some value B";
This is more concise, more readable and safer than:
StringBuffer buff1 = new StringBuffer("");
buff1.append("some value A");
buff1.append("some value B");
I say 'safer' because a String is immutable and a StringBuffer is immutable, so there's no risk of the String accidentally being changed after construction.
Aside
It's a common misconception that "concatenating Strings in Java is bad". While it's true that you shouldn't write code like this
String buff1 = "foo";
buff1 += "some value A";
buff1 += "some value B";
It's perfectly acceptable to write code like this:
String buff1 = "foo" + "some value A" + "some value B";
when the concatenation is performed in a single statement the code will be optimized to:
String buff1 = "foo some value A some value B";
Upvotes: 3
Reputation: 5605
It's very likely that code was generated by some refactoring tool and the coder wasn't bothered to remove the redundant lines.
Upvotes: 4
Reputation: 4788
The only reason I can think of why he'd do that is readability (though even that seems a bit strange).
Upvotes: 0
Reputation: 57284
Nope.
And given that they're hardcoded strings, it'd be identical to write
buff1 = new StringBuffer("some value Asome value B");
BTW, it's a bit more efficient to use a StringBuilder rather than a StringBuffer (and the API is identical).
Upvotes: 5
Reputation: 15824
No you don't need that append("")
. You also do not need to initialize the StringBuffer with a String. new StringBuffer();
will work fine.
Upvotes: 4