borrowing Constants

D

Daniele Futtorovic

If you have some code like this:

class A
{
static String VERSION = "1.0b";
}

and
class B
{
static String VERSION = A.VERSION;
}

When you use Class B, does all of class A get instantiated?
Does all of class A get put in B's jar?


If so, it suggests you are better off to have a tiny common class and
have A and B reference it.

If someone showed me that code (class B) and told me they didn't intend
to include class A in the runtime, my first question would be: "then why
do you reference it?"

If you want to decouple, decouple properly. Use a common class, a
resource file, a service provider interface, whatever. But don't rely on
intrinsics -- even if in this case those are fairly basic and
well-understood intrinsics. That's just begging for trouble.
 
A

Arne Vajhøj

restating, if the expression for A.VERSION cannot be evaluated an
compile time, even final won't rescue you from having to include both
A in your jar and indirectly loading A when you load B.

So the rule of thumb use static final with values known at compile
time to avoid needless class loading. But be aware, you must recompile
B if the value of A.VERSION changes, or you will get the old value.

Another rule of thumb may be, instead of cross linking classes with
references to each others constants, refactor out the constants to a
third class, and reference it or extend it.

In a number of my projects I have a Config class where everything
constant (possibly computed) needed to configure a program for a
particular use are collected.

Rule of thumb: don't worry about the microseconds spend on class
initialization and spend the time on something relevant.

The requirement to recompile B if A is changed for constants
can be a much more severe problem than class init.

Arne
 
A

Arne Vajhøj

Generally, no. It's been tried, and found to not work well. A class full
of unrelated constants is just that: a class full of unrelated
constants. Put the constants where they belong.

That is very basic good design.

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

constructing a constant HashMap 19
Java control panel anomaly 2
code generation for the ternary operator 33
in praise of type checking 33
New Java releases 1.6.0_29 and 1.7.0_01 3
@see scope 6
Ubunto 74
Where am I? 10

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top