r/java 10d ago

Value Classes Still Need Compiler Sympathy

https://johan-sjolen.github.io/post/compiler-sympathy/compiler-sympathy/
89 Upvotes

57 comments sorted by

View all comments

Show parent comments

4

u/FirstAd9893 9d ago

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.

1

u/cowslayer7890 8d ago

If they prohibited it then they wouldn't be able to convert existing classes in the JDK to value classes, which would be an obvious loss

Also making it mean .equals doesn't really work when the first thing most equals methods do is check ==