Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the pros and cons of having private methods return String instead of passing around a StringBuilder [closed]

Tags:

java

string

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!

like image 704
Todd R Avatar asked Sep 16 '11 15:09

Todd R


1 Answers

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.

like image 144
Peter Lawrey Avatar answered Oct 06 '22 20:10

Peter Lawrey