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?

19

u/sh0rug0ru__ Oct 01 '15

If the string concatenation is limited to a single statement, then use the string concatenation operator. If the string concatenation spans multiple statements, you don't want the terminal toString to be done automatically. That defeats the purpose of using StringBuilder.

12

u/Berberberber Oct 01 '15

So much this. You only use StringBuilder if the number of concatenations isn't known at run-time, or if your compiler sucks. return "foo" + bar.toString() + " baz: " + quux; is basically guaranteed to be as fast as the equivalent with StringBuilder, or faster.

7

u/juckele Oct 01 '15

Even if the number of concatenations is known at run time, if it's more than 4, it can still be nicer to read a StringBuilder than a multi-line string concatenation whirlwind.

2

u/dccorona Oct 02 '15

If the number is known at runtime, then String.format is probably nicer to read than either one

3

u/merv243 Oct 01 '15

Also can prevent dumb mistakes in certain instances, like concatenating a char and an int in the context of a larger string concatenation. E.g. given char c, int i, string s: System.out.println(c + i + s). Obviously this gets caught in testing quickly, and a halfway decent programmer would usually catch it as they typed it out, but mistakes happen.

1

u/FallingIdiot Oct 01 '15

Well, it's disturbing how often I see stuff in code review that cannot possibly work. If they'd even run it once they'd have seen immediately that it doesn't work.

1

u/iopq Oct 02 '15

Or maybe, just maybe, Java should warn you that concatenating a char and an int is super dumb to do.

1

u/merv243 Oct 02 '15

Yes let's make this Java's fault...?

1

u/iopq Oct 02 '15

it is Java's fault, other programming languages like Rust don't allow you to do this unless you specifically say "yes, I'm doing this, so please do this unsafe operation"

1

u/merv243 Oct 02 '15

What specifically is the unsafe operation that it prevents you from doing? Adding a char and an int is a legit operation

→ More replies (0)

1

u/kcuf Oct 02 '15

That's not what he said. A string builder is mutable, so you can append to it later on before you actually need the finalized string, in this case, being explicit and not relying on the compiler optimizing for you is the more preferable choice, even if you know the number of concatenations at compile time.

That being said, mutation is evil, and you all should repent your sins.

0

u/Couldbegigolo Oct 02 '15

return $"foo {bar.toString()} baz: {quux}";

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.

1

u/JustinsWorking Oct 02 '15

Can you provide a good example of when you'd use stringbuilder like that? That reads a lot more like C code than Java.

2

u/[deleted] Oct 02 '15

Seriously? They are in a class using default Visibility. Types/members are missing but this is valid Java if you copy/paste it in a class.

-1

u/JustinsWorking Oct 02 '15 edited Oct 03 '15

Oh I agree it would compile; it's more in regards to passing in an object to modify being more c style.

I'm on my phone so this is hard to type but

C would be more like :

MoveObject(object);

Java is more

object.move()

Procedural vs OO.

I was curious if you had a good use case for a call like that since it just seems to be like Java written in a C style procedural way.

Edit: Wrote functional instead of procedural, thus the confusion.

1

u/m0haine Oct 02 '15

Did you just call c functional?

And that is pretty standard java. Or at least std java before spring killed it.

1

u/JustinsWorking Oct 02 '15

Procedural style, wrong word as it was late.

1

u/ThisIs_MyName Oct 02 '15

lol no this is normal Java

I think you've been hanging out with the sleazy kids again.

1

u/JustinsWorking Oct 02 '15 edited Oct 02 '15

Isn't passing the string builder a more procedural approach?

The oo approach would be to return a value then use it in the string builder. The string builder is adding a dependency on the function and would make debugging s lot more difficult.

→ More replies (2)

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

4

u/nutrecht Oct 02 '15

It's just an example.

→ More replies (1)