3 ms·
There's a difference between something being possible vs supported. In C/C++ you can have a type, and a const version of that type. In Java you can't define a c
by karmakaze 2y ago
There's a difference between something being possible vs supported. In C/C++ you can have a type, and a const version of that type. In Java you can't define a class and automatically be able make a reference to a const object of that class. You can make a final reference, but that only means you're always referencing the same (mutable) object. You could you use final fields for the entire object, but then you have to make another type for the mutable kind, or builders to go from one to an other. Another example is Unmodifiable collections, which are only views on modifiable ones, so you can't be sure it's not modified. A language that supported immutability would come with some of these batteries included.
There are places to use encapsulation with mutability, such as simulations, but having hidden mutable states is not desirable property when constructing rapidly changing applications.
I do my best to keep things sane when working with a Java or Ruby or what have you codebase, but I don't pretend it's something it's not. Just do the best that the codebase and organization can tolerate.
- layer8 2y agoRight, you can’t turn a mutable object into an immutable object when other references to the mutable interface already exists. Const as in C/C++ is certainly a useful feature that Java lacks, but it’s quite a leap from that to claiming that Java doesn’t support true immutability. I develop Java applications with immutability as the default, and it works quite well. The lack of the abive-mentioned feature is not a critical obstacle. Regarding your point about collection views, const references are often also just views on mutable objects, and this poses no particular difficulty. And you can implement truly immutable collections in Java if you really insist on it.