I'm trying to understand what value objects change in Java. Is deciding whether an object needs identity enough, and what should I expect for performance?
JEP 401 is coming to JDK 28 as a preview. When should I use value classes?
Answers
Start with what makes two instances interchangeable. A point with the same coordinates or a wrapper around an identifier may be a good fit if its data is all that matters. A value class gives up object identity, so two separately created instances with the same component values can be treated as the same value.
That is a different question from whether you happen to have an equals method today. Check whether callers rely on a particular instance being distinct, even when its data matches another instance.
Reply to this answer
Watch out for identity hiding in the API. If instances are used as locks, as keys in an identity map, as unique markers, or compared specifically to see whether they are the same object, a value class is the wrong fit.
Mutable objects and objects that act as the central reference to a larger structure also deserve caution. Records may be candidates, but a record declaration alone does not prove that its components or the objects they reference are deeply immutable.
Reply to this answer
I would not rewrite collections for speed just because this preview exists. The compiler can already optimize some collection access, and unboxed storage for value types involves additional work on null-restricted types. Benchmark the actual workload rather than assuming an array of value objects will beat an ArrayList.
9t~corkledger_562:
So the language feature and the storage optimizations are related, but they are not all delivered by the same proposal.
Reply to this answer
Add your answer
Answers are reviewed before publication.
5b~copperbookmark_372:
The acronym JEP means JDK Enhancement Proposal. This one is a preview, so it is a chance to try the feature rather than assume its design is permanent.