Re: Class Constants - pros and cons
On Sun, 25 Jul 2010, Lew wrote:
Magnus Warker wrote:
It's the readibility of the code.
With constant classes I can write something like this:
public void setColor (Color color)
{
if (color == Color.WHITE)
Lew wrote:
No. That would be a bug. You'd write
'if ( color.equals( Color.WHITE ) )'.
Joshua Cranmer wrote:
To be pedantic, it would not be a bug if the Color class were written in
a certain way, i.e., there is no other Color instances other than those
in Color's static instance variables.
You are wrong, this once. (In your case, an extremely rare occurrence.)
It's impossible to enforce that for all clients 'color' is assigned the
exact instance, therefore that == will work if the static variables are
Strings. It's all too easy to accidentally push in a different constant
String from some other class, as outlined in my other response, or by
other means to create a different instance of a String that you intend
even with the correct value. So yes, to be pedantic, using == would be
a bug waiting to happen, as would using String constants when enum
constants are so much safer (and guaranteed to work with == ).
I won't argue with you about Strings.
But Joshua was talking about using instances of Color, where those
instances are singletons (well, flyweights is probably the right term when
there are several of them), exposed in static final fields on Color, and
the class is written in a certain way, which i take to mean having a
private constructor, not creating any instances other than those in the
statics, and implementing readResolve. In that case, how can there be
pairs of instances for which .equals is true and == isn't? Colour doesn't
make such instances, no other class can make such instances directly,
serialization won't, and sun.misc.Unsafe is a foul.
Indeed, this is exactly what enums do, so why do you think classes can't?
tom
--
If goods don't cross borders, troops will. -- Fr