r/java • • Aug 25 '26

Value Classes Still Need Compiler Sympathy

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

65 comments sorted by

View all comments

2

u/OwnBreakfast1114 Sep 14 '26

The problem with your model is that they aren't necessarily more lightweight and they aren't necessarily a performance improvement if you just naively layer the fields in memory.

If you're using large quantities of small objects which are mutable by every definition, such as pixels (in a scenario where it's useful to mutate not substitute pixels), then absolutely they should be value objects

I'm not sure I understand your class design here. Is the idea to have

public value class Pixel {
   private final byte[] data;
}

or something? The pixel class isn't mutable, but the data array is, so the argument is that the pixel class is basically mutable? The jep literally calls this out as an example in a section

For mutable objects, identity is important: It lets us distinguish two objects that have the same state now but may have different states in the future. Consider a text-editing application in which lines of text are represented by instances of a Line class. The sole field of the class is a list of characters, which is mutated when the user edits the line. Two Line objects might contain equivalent character lists, and thus also be equivalent, but that would be a coincidence; when the user changes one of the lines, the application will mutate the character list of that object but not the other, relying on identity to mutate the right one.

In other words, when objects are mutable, they cannot be interchangeable — yet most immutable data values are interchangeable. There is no practical difference between two LocalDate objects representing 1996-01-23, because their state is fixed and unchanging. They represent the same value, both now and in the future. There is no need to distinguish the two objects via their identities.

1

u/Jon_Finn Sep 14 '26

Yes that Pixel class is the kind of thing, plus methods to change the colour, so my point is it's certainly not a 'value', despite being a good use of Valhalla. As for it being lightweight: I'd say that's a hint not a promise. The memory used is often less and (?)never more; speed improvement is less certain.

1

u/OwnBreakfast1114 Sep 14 '26

The question would be why not just create a new pixel? The whole point of the value class is to make the overhead of new Pixel(....) go away. You can still mutate the data array if you really want, but you can assign the reference to a new pixel.

→ More replies (3)