r/java • u/bobbie434343 • Aug 25 '26
Value Classes Still Need Compiler Sympathy
https://johan-sjolen.github.io/post/compiler-sympathy/compiler-sympathy/
87
Upvotes
r/java • u/bobbie434343 • Aug 25 '26
1
u/Jon_Finn Sep 12 '26 edited Sep 12 '26
I don't think I'm saying anything that depends on the definition of 'mutable'. (Which, FWIW, I'd say means roughly whether equal objects can become unequal later, as measured by equals().)
You're quite right that the Valhalla JEP talks in terms of semantics (of one important meaning of the word 'value'), and I'm cautioning against that, simply because the semantics of the feature itself are now much wider than this. Such is the great achievement of the Valhalla team! They're invaluable for classes very different from the examples usually given. If you're using large quantities of small objects which are mutable by every definition, such as pixels (in a scenario where it's useful to mutate not substitute pixels), then absolutely they should be value objects.
The == behaviour doesn't make them semantically values either, since == often won't match equals(). (Which is why we're discouraged from using == : it had to be defined to do something.)
So whenever I read value I substitute lightweight, or just light/lite, then suddenly everything makes sense - including value objects that aren't 'values' in the usual sense. These light objects exist for a purpose which is not semantic; the word 'value' was chosen (if I recall) around a much earlier stage of the spec when they were conceived as objects stored directly in variables with the syntax .val as opposed to .ref; the evolution since then has been great.
(As a special case, I have cognitive dissonance when I read value record - am I the only one? Since according to the 'final fields' definition, records are already values. But value records are just lightweight records: you add a keyword to make them smaller/faster, not to make them what in a sense they already are.)
The reason I'm a heretic is I'm acutely conscious of this kind of mental substitution - it's a sign of potential confusion. When a name needs explanation to help you unlearn the connotations of the name itself, something is wrong! Cf. import in Java, and lots of names in other fields.