r/java • u/davidalayachew • Jan 06 '26
One step closer to Value Classes!
https://mail.openjdk.org/pipermail/porters-dev/2026-January/000844.html
181
Upvotes
r/java • u/davidalayachew • Jan 06 '26
View all comments
Show parent comment
20
u/segv Jan 06 '26 edited Jan 06 '26
Others have covered the mechanics of value-based classes, but from programmer's perspective the biggest advantage is that it allows you to easily distinguish pieces of data that may have the same type but different meaning - e.g.
long customerIdmeans something vastly different thanlong orderId.The problem is that the compiler does not know the that meaning, but since both variables have the same type, it will not catch them being misused - for example swapped around in a function call.
To get the compiler to help you catch such mistakes, you had to wrap these values to give them distinct types that the compiler could understand - e.g.
record CustomerId(long id){}or alternatively by using regular classes, both being abstractions that have a slight cost (creating a new object) at the runtime.This method of distinguishing values works super well in larger codebases that deal with complex domains, but mind that it is nothing new by itself - you could've implemented that pattern from the very first versions of Java and, heck, there are even libraries that made it slightly less annoying to deal with (see valueclasses library that was posted in that 'library that saved your butt' thread not too long ago). JDK itself already includes some value-based classes like
java.time.LocalDateas well.The mailing list announcement in OP's link is a big deal because bringing optimizations for value-based classes to the JVM level should slightly improve performance and slightly reduce memory usage of applications, both new and old.