dev@glassfish.java.net

Re: should constants be used in a modularized system?

From: Bill Shannon <bill.shannon_at_sun.com>
Date: Thu, 20 Mar 2008 14:31:56 -0700

Lloyd L Chambers wrote:
> In Glassfish V3 the system is highly modularized. Compiling one module
> against another might mean using static constants eg:
>
> // module B using org.glassfish.foo.bar from another module A
> import org.glassfish.foo.bar.CONSTANT1;
>
> ...
> doSomething( CONSTANT1 );
> ...
>
> If I understand correctly, java constants are compiled into the
> resulting bytecode.
>
> So if the constant is later changed in the defining module, code
> compiled against that module does *not* pick up the new value unless it
> is recompiled.
>
> In short, in a modular system, should constant values be fixed at
> compile time, or picked up dynamically at runtime? If they are to be
> dynamic, then our constants need to be written as methods eg:
>
> public static String getCONSTANT1();
>
> *not*
>
> public static final String CONSTANT1 = "val"
>
>
> Of course, there might not be a hard and fast rule. But if a module is
> newly-built and has new values for its constants, it might be reasonable
> to expect dependent modules to use the new values.

Yes, we should all understand this. Primitives and String constants
are stored by *value*, not name. Once you choose a value for one of
these constants in a public API (across module boundaries), you're
committing to it, no matter what name you might use.

Many of these constants should probably be enums, which don't have this
problem.

String constants should really only be used for things that are externally
defined and really won't change. Otherwise, if it can change, it's not
really a constant! :-)