Two comments on the Constants API

mark.reinhold at oracle.com mark.reinhold at oracle.com
Mon Jun 4 16:39:59 UTC 2018


I realize this is coming a bit late in the game, but after reviewing the
Constants API in detail I have two design comments.

First -- and this is the easy one -- consider changing the package name
to from `java.lang.invoke.constant` to `java.lang.constant`.

As I understand it, this API is not intended just to support constant
folding and ldc/invokedynamic intrinsics but, also, to serve as a common
API that libraries and tools outside of the JDK can use to represent and
manipulate the information in constant pools.  As such it shouldn’t be a
subpackage of `java.lang.invoke`, since it’s useful beyond the scope of
that package.

Second, please consider alternative approaches that don’t change the core
classes that millions of Java developers use every day (e.g., `String`)
by making them implement two new, obscure, low-level interfaces that are
only of direct interest to the hundreds of developers who will use the
Constants API.  To wit:

    public final class String
        implements java.io.Serializable, Comparable<String>, CharSequence,
                   ConstantDesc<String>, Constable<String>
    {
        ...

Explaining to a non-expert developer why `String` implements both
`Comparable` and `CharSequence` is pretty straightforward.  (Explaining
why it implements `Serializable` is less so because ...  serialization.)

I’d be at a loss, though, as to how to explain `ConstantDesc` and
`Constable` to anyone who’s not actually going to use the Constants API,
or at least read through its Javadoc, as most developers will never have
a reason to do.  These wouldn’t look out of place in a more academic
language, e.g., Haskell, but that’s not what Java is.

I’m not sure what the best way to fix this might be.  Perhaps you could
fold these two interfaces into one interface with a name that’s more
meaningful to non-experts.  Another alternative would be not to change
any core classes to implement any constant-specific interfaces and just
do it all through static methods in the constants API -- but then you
wouldn’t be able to leverage the type system, and that would be less
than ideal.

At any rate, if fixing this means that the Constants API is a little
less convenient for expert-developer use then I think that’d be the
right tradeoff.

- Mark


More information about the amber-dev mailing list