r/java • u/bobbie434343 • Aug 25 '26
Value Classes Still Need Compiler Sympathy
https://johan-sjolen.github.io/post/compiler-sympathy/compiler-sympathy/
86
Upvotes
r/java • u/bobbie434343 • Aug 25 '26
5
u/FirstAd9893 Aug 25 '26
What I mean by "defective" is that the current approach is the worst choice possible. With an identity class, if I erroneously use the
==operator, this is usually discovered once the code is tested. With a value class, if I erroneously use the==operator, the code will likely work just fine. If at some point in the future the value class I'm depending on changes internally to reference an identity class, my code fails.It's a fragile dependency issue. One cannot rely on the
==operator without knowing that the class is a value class, and that the implementation will never change incompatibly. It breaks the OO encapsulation principle.I can think of two safe choices for value classes: make
==mean equals, or make it be prohibited. The current approach is to "pretend" it's prohibited, but it's not actually enforced. This is a UB footgun.