Consider a class with a "buildMessage" method (something like):
public class MessageBuilder {
public String buildMessage() {
//Build up the message and return
//
//Get the header
//Get the body
//Get the footer
//return
}
}
When we build up our message, it's preferable to build up strings with a StringBuilder (or similar buffering object) instead of just concating a bunch of strings together. But does that mean you lose this benefit returning String instead of taking your StringBuilder as an argument?
In other words, this reads nicely and is easy to understand:
private String getHeader() {
StringBuilder builder = new StringBuilder();
builder.append("Hello ")
.append(this.firstname)
.append(",\n");
return builder.toString();
}
That seems more natural to me than being forced to pass in a StringBuilder, but we could also write:
private void appendHeader(StringBuilder builder) {
builder.append("Hello ")
.append(this.firstname)
.append(",\n");
}
The first option makes it possible to use the "get" methods, even if the intent is not to append the returned value to a buffer. It also makes the public method easy to understand:
public class MessageBuilder {
public String buildMessage() {
StringBuilder builder = new StringBuilder();
builder.append(getHeader())
.append(getBody())
.append(getFooter());
return builder.toString();
}
}
While using the second option leads to:
public class MessageBuilder {
public String buildMessage() {
StringBuilder builder = new StringBuilder();
appendHeader(builder);
appendBody(builder);
appendFooter(builder);
return builder.toString();
}
}
My question is whether or not the first option suffers from the same memory issues as just "concating" + " strings" + " together". I'd be interested in hearing opinions about which reads better (because if there's a clear winner as to which one's cleaner and easier to read, that would weight heavily in it's favor), but I'm curious about the efficiency of it too. I suspect there's little to no difference, but wonder if anyone "knows" about the costs associated with each approach - if that's you, please share!
Reusing a StringBuilder is more efficient CPU wise. However, I doubt it will really matter.
You should do what you consider the most natural and clearest approach is. (Which appears to be StringBuilder from what you are saying)
Performance alone is less often a good reason to do something than many people think.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With