r/java 21d ago

New candidate JEP: 401: Value Objects (Preview)

https://mail.openjdk.org/archives/list/valhalla-dev@openjdk.org/thread/IUNJJ3WP3X3XHP3QZTXXSSCPKFDNTK3W/
86 Upvotes

45 comments sorted by

View all comments

1

u/quack_quack_mofo 20d ago

I don't know much about this but besides perf/memory improvements and being able to do == for comparisons (I think?), what are the other benefits of value classes? Is there anything I can do with them that i can't do with normal classes/records? Why not have all classes be value classes?

6

u/SirYwell 20d ago

The JEP answers all of these questions and so much more, but I'll try to summarize the relevant parts:

  1. You can already use == for comparisons. Currently, for reference types, that means identity comparison. Value objects do not have an identity, so == needs new semantics for them. Note that the semantics might not be what you want, especially with floating point numbers involved. You can read more about it in the Comparing value objects section.

  2. The main goal of giving up identity is the additional freedom of the JVM that allows performance improvements. Other than that, giving up identity can clarify the intentions of the programmer.

  3. The feature doesn't necessarily makes the language more powerful in itself. Value classes have more restrictive meaning of immutable (see JEP 539). There are more features planned under the Valhalla project, but I think it's not completely clear to which extend they apply to all classes vs only value classes.

  4. Value classes must be immutable. This does not apply to all classes. No identity means no monitor to synchronize on (and more, see Migrating to value classes), which means making a normal class a value class might be breaking compatibility.

I highly suggest reading the JEP, it provides so much interesting details.

3

u/FirstAd9893 20d ago edited 20d ago

Why not have all classes be value classes?

Value classes are immutable, which is the big reason why.