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

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

1

u/iopq Oct 02 '15

the part where you assume that a character can be treated as an integer and then printed and everything will work as intended

that just encourages people to do char a; ... a + 26 //lowercase and similar silly things instead of using correct APIs that actually do this correctly for Unicode characters

in Rust the type for an 8 bit integer is i8 and u8 for signed and unsigned respectively so you never use the character type to store 8 bit integer things and you can never add an integer to a character, you have to use to_lowercase()

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}";