3 ms·
If you mark all fields and variables in Java as final, you get pretty much this experience? If I could go back in time and unilaterally make one change to Java
by stickfigure 8y ago
If you mark all fields and variables in Java as final, you get pretty much this experience?
If I could go back in time and unilaterally make one change to Java, it would be to make `final` default. But if you just get in the habit of using it (the IDE helps), non-final variables look broken. And once objects have all-final fields, immutability just starts spreading upward in your code.
- mcintyre1994 8y agoI’m a bit surprised they haven’t copied Scala’s case class, where you get immutable fields by default and helpers to copy with updated fields, along with a sane hash and equality implementation. Making immutability easier than the alternative makes a huge difference in practice.
- zmmmmm 8y agoUnfortunately unlike C++ etc constness doesn't propagate inside objects marked final. So final List x = new ArrayList() stops x being reassigned but does nothing to stop the downstream code from mutating the contents of the list.
- xxs 8y agofinal List<?> immutable = Collections.immutableList(x)... and pass it around. Never expose your collections directly (unless you are willing to go copy on write and immutable objects inside the collections, the latter is very welcome, though)
- stickfigure 8y agoAlso, if you want to go 'whole hog' you can use any of the functional/immutable collection libraries like vavr, functionaljava, or jimmutable.