Consider a class with the "buildMessage" method (something like):
public class MessageBuilder { public String buildMessage() {
When we create our message, it is preferable to create strings using a StringBuilder (or a similar buffering object) rather than just instantiating a bunch of strings. But does this mean that you are losing this advantage by returning a String instead of taking your StringBuilder as an argument?
In other words, it is well read and easy to understand:
private String getHeader() { StringBuilder builder = new StringBuilder(); builder.append("Hello ") .append(this.firstname) .append(",\n"); return builder.toString(); }
It seems more natural to me than being forced into a StringBuilder, but we could also write:
private void appendHeader(StringBuilder builder) { builder.append("Hello ") .append(this.firstname) .append(",\n"); }
The first option allows you to use get methods, even if the intention is not to add the return value to the buffer. It also simplifies the understanding of the social method:
public class MessageBuilder { public String buildMessage() { StringBuilder builder = new StringBuilder(); builder.append(getHeader()) .append(getBody()) .append(getFooter()); return builder.toString(); } }
When using the second option:
public class MessageBuilder { public String buildMessage() { StringBuilder builder = new StringBuilder(); appendHeader(builder); appendBody(builder); appendFooter(builder); return builder.toString(); } }
My question is whether the first option depends on the same memory problems as "concinating" + "strings" + "together". I would be interested to hear opinions about what reads better (because if there is a clear winner in that one is cleaner and easier to read, it would greatly affect its benefit), but I am also interested in the effectiveness of it. I suspect that little does not matter there, but ask yourself if anyone knows about the costs associated with each approach - if this is you, please share it!
Todd r
source share