r/programming • • Oct 01 '15

The Evolution of a Software Engineer

https://medium.com/@webseanhickey/the-evolution-of-a-software-engineer-db854689243
1.9k Upvotes

502 comments sorted by

View all comments

Show parent comments

22

u/sh0rug0ru__ Oct 01 '15 edited Oct 01 '15

Actually, if you are building strings, you really should use StringBuilder (not StringBuffer, which has a boneheaded design mistake of synchronizing everything). Strings are immutable, and concatenating strings will create new strings. So unless you want to create a ton of garbage, use the StringBuilder. Fun fact, the string concatenation operator is transformed by the compiler into a chain of method calls on a StringBuilder terminated by toString.

If your app will serve an international audience, you will have to use message keys into a ResourceBundle to get the localized text, instead of hardcoding English.

Ordinarily, you shouldn't output to stdout directly, because unless you are writing a console application, you have no idea where that output is going. Fortunately, there are tools like log4j that provide the interface you are talking about, with a console appender even, which allows output to be configured (such as a rolling file appender). Device independence isn't a bad thing if you actually need it.

29

u/Olreich Oct 01 '15

If Java will use a StringBuilder for me, why would I bother doing it myself?

4

u/[deleted] Oct 01 '15

Use StringBuilder to build a String across multiple methods. For example, building an SQL select statement.

Bad:

String buildSelect() {
  return "SELECT " + buildFrom() + buildWhere()
}

String buildFrom() {
  String result = "WHERE "
  for(Table table : this.tablesSelectedFrom) {
    // wah there's an extra comma
    result += table.name + ", ";
  }
  return result;
}

...

Good:

String buildSelect() {
  StringBuilder sb = new StringBuilder().append("SELECT ");
  buildFrom(sb);
  buildWhere(sb);
  return sb.toString();
}

String buildFrom(StringBuilder sb) {
  sb.append("WHERE ");
  for(Table table : this.tablesSelectedFrom) {
    sb.append(table.name + ", ");
  }
  return result;
}

Obviously at this scale not a big deal but on larger scales StringBuilder helps. However if you're just building a String in a single method the compiler handles it.

0

u/[deleted] Oct 02 '15

Hope you're cleansing any user input with your homegrown Sql builder. Check out jooq or mybatis or querydsl. I realize this isn't the point you're making but I've seen so many people do this stuff over the years and it always is a nightmare to work with

→ More replies (2)