DEV Community

Discussion on: Why I’m So Frustrated With Go

Collapse
 
klnusbaum profile image
Kurtis Nusbaum
Collapse
 
rkuris profile image
Ron Kuris

I think even these discussions miss a key point. I can't tell you how many times I've had, in Java, someone just throw "final" on their class because they thought nobody should extend it. I've had to copy entire classes because I couldn't use something from a library more times than I can count just for this reason.

Even "String" in java is final and immutable. I want mutable strings, for all the reasons mentioned in many of these posts -- much faster, easier to deal with, etc. Because of someone's idea that all strings should be immutable, I end out constructing tons of objects that I don't need, and compiler writers spend thousands of hours improving the optimizer to avoid these allocations, and programmers resorting to libraries with buffers and such in order to add simple strings together, all because someone thought string should be immutable.

Thread Thread
 
jimleroyer profile image
jlr

I also don't like the habit of certain programmers to define all of their Java classes as final, but that is not immutability of object instances that the author refers to (preventing class extension vs preventing modification of objects at runtime). I think it's a valid rant but that sounds like a different topic.

Regarding mutable Strings in Java, I wonder why you had to use libraries. There are StringBuffer and StringBuilder just for that in core Java (former is present since JDK1.0), sitting alongside String (in java.lang package).

On the topic of immutability and specifically String, James Gosling gave an explanation back in 2001: artima.com/intv/gosling313.html

Performance (there are cases where immutability can provide more performance) and security basically were his two main reasons for making String immutable. I particularly like this quote:

You end up getting almost forced to replicate the object because you don't know whether or not you get to own it.

That's obvious for C, C++ or/and Rust programmers. Maybe less when we are used to work with a VM that does most of the memory allocation and ownership management.