3 ms·
> records/pure immutable data classes Example? As far as I know, Java has final, which means that particular reference can't be re-assigned, but the object re
by kaashif 4y ago
> records/pure immutable data classes
Example?
As far as I know, Java has final, which means that particular reference can't be re-assigned, but the object referred to remains mutable. You have to resort to e.g. having separate immutable and mutable interfaces or whatever to restrict a someone from mutating your object.
If you want an immutable data class more than one level deep, I don't know if there's a convenient way to do that like there is with const in C++ (or the default behaviour in Rust).
But I'm not a Java programmer, I haven't really kept up with the language. Happy to be proven wrong.
- gavinray 4y agoJDK 17 record classes: record User(String name, Integer age, Boolean isActive) {} https://docs.oracle.com/en/java/javase/18/language/records.html https://docs.oracle.com/en/java/javase/18/language/records.h...
- kaashif 4y agoIf you have mutable members you can still absolutely do myRecord.member().methodThatMutates(). The only way to stop this is to remove the mutable methods from the interface entirely, which is what I'm complaining about.
- kaba0 4y agoYou are right, though I seldom find it a problem in practice. Also, OOP sort of makes immutability hard to define (e.g. is a getter with an internal counter of accesses immutable? In a way, it is. Also, Rust’s internal mutability pattern is similar). Nonetheless, recently more and more standard classes are made deliberately immutable, and there was a proposal for frozen arrays as well (not sure on their status).
- kaashif 4y ago> You are right, though I seldom find it a problem in practice. Although it's easy to to tell people that mutation is confusing and to avoid it, enforcing that is much easier if the compiler is on your side and will prevent mutation with const. I've encountered unnecessary mutation (introducing implicit assumptions on the order of calls, and making things more confusing) constantly in both Java and C++, but enforcing const in C++ cuts down on that. Or at least, it forces a const_cast which I won't approve without a really good reason. You're right about Rust of course, internal mutability is possible and maybe even common with RefCell, but culturally it seems like that's avoided. On the other hand, mutability is extremely common in Java. Maybe I'm just traumatized from some of the horrific code heavily using mutation I've seen over the years.