Hacker News new | past | comments | ask | show | jobs | submit login

I disagree on both accounts. It’s not difficult to code truly immutable classes in Java. And encapsulation is beneficial regardless of mutability.



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.


Right, 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.


It’s difficult in the sense that somebody consuming your class will sooner or later start relying on reflection to do something with it they shouldn’t (because they can), and then when you make a change in the future it will cause breakage downstream. Records solved this for some cases at least.

More important imo is that the standard collection classes can’t even be set to immutable with the final keyword. Sure you can use something else, but professionally you are going to have to deal with them most of the time still.


Yeah they seem to be trying to force the conversation into encapsulation == mutability when that flatly is just not true. There are tons of immutable objects that benefit from encapsulation and there is plenty of internal immutable state that you would want to encapsulate and not just give out.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: