Value class with fields mutable as non default
Anderson Vasconcelos Pires
andvasp at gmail.com
Mon Jan 24 18:26:02 UTC 2022
Hi guys,
I have in mind that identity is a heavy thing in Java. So I would avoid
identity classes as much as possible. The object model [1] instructs us to
use identity classes for the following cases:
*Use identity classes when we need mutability, layout extension, or
locking;*
My naive understanding tells me that fields of a value class could be
mutable keeping the standard as immutable. I know that value classes being
immutable is beneficial to the JVM but I am wondering if it would have some
advantage in having this possibility too.
Considering the user case below where I have such a business logic like a
cache data update. My doubt is if the situation below would be good to use
identity class, value class or value class with mutable fields?
value class ManyFields {
public String field1, field2, field3, field4, field5;
}
var manyFieldsById = new HashMap<String, ManyFields>();
Using value class:
var manyFields = manyFieldsById.get("xxx")
manyFields = manyFields.createAnotherInstanceSettingField1("anotherValue");
manyFieldsById.put("xxx", manyFields)
Using identity class or value class with mutable fields:
[value] class ManyFields {
public *non-final* String field1, field2, field3, field4, field5;
}
var manyFields = manyFieldsById.get("xxx")
manyFields.field1 = "anotherValue"; // do not create another instance and
do not put it in the Map.
In this scenario would it be better to use value class, identity class or
value class with mutability if mutability would be possible?
[1] -
https://openjdk.java.net/projects/valhalla/design-notes/state-of-valhalla/02-object-model
Thanks for your time and please let me know your thoughts about this.
Anderson.
More information about the valhalla-dev
mailing list