Please don't restrict access to the companion-type!

Gernot Neppert mcnepp02 at googlemail.com
Thu Jun 30 07:33:42 UTC 2022


I've been following the valhalla-development for a very long time, and have
also posted quite a few comments, some of them raising valid concerns, some
of them proving my ignorance.

This comment hopefully falls into the first category:

My concern is that allowing access-restriction for a value-type's
"companion-type" is a severe case of "throwing the baby out with the
bathwater".

Yes, I know what it is supposed to achieve: prevent users from accidentally
creating zero-initialized values for value-types "with no resonable
default".

However, the proposed solution of hiding the companion-type will force
programmers to use the reference-type even if they do not want to.
Please have a look at the following class "Accumulator". It assumes that
"Sample" is a value-class in the same package with a non-public
companion-type.
The Javadoc must now explicitly mention some pitfalls that would not be
there if "Sample.val" were accessible.
Especially the necessary precaution about the returned array-type is rather
ugly, right?!

public class Accumulator {
   private Sample.val samples;

/**
Yields the samples that were taken.
Note: the returned array is actually a "flat" array! No element can be
null. While processing this array, do not try to set any of its elements to
null, as that may trigger an ArrayStoreException!
*/
public Sample[] samples() {
    return samples.clone();
}
}

To sum it up, my proposal is:

1. Make the companion-type public always.
2. When introducing value-classes, document the risks of having
"uninitialized" values under very specific circumstances (uninitialized
fields, flat arrays).
3. Let the compiler treat fields of companion-types like final fields
today, i.e. enforce initialization.
4. The risk of still encountering uninitialized fields is really really
low, and is, btw, absolutely not new.
4. Provide the users with a convenient API for creating arrays with all
elements initialized to a specific value.
5. In Java, one could possibly also use this currently disallowed syntax
for creating initialized arrays: new Sample.val[20] { Sample.of("Hello") };
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/valhalla-spec-comments/attachments/20220630/b1bcec39/attachment.htm>


More information about the valhalla-spec-comments mailing list