Re: final fields of an enum that refer to
Andreas Leitgeb wrote:
Daniel Pitts <newsgroup.spamfilter@virtualinfinity.net> wrote:
I think that the best designed approach is to externalize the relationships:
private static final Map<Thing, Thing> mates;
static {
final Map<Thing, Thing> matesMap = new EnumMap<Thing, Thing>();
...; matesMap.put(T42,T43); ...
mates = Collections.unmodifiableMap(matesMap);
}
This removes cyclic dependencies from your design, and externalizes the
configuration of mate.
An elegant approach, indeed. Thanks for sharing.
Also:
// To help filling the mates-Map, (or for direct use):
private Thing[] matesArr = { T2, T1, T4, T3, ... };
That is bad design for at least two reasons. The compiler won't tell
you if you have an odd number of mates, and arrays should be avoided if
possible anyway. ;-)
Not to mention, if I were maintaining this and had to "change T42s mate
to be T68, and change t68s old mate to be t42s old mate". Finding them
in the array would be one thing, but then figuring out if T42 was on the
left or right of its mate would be a pain.
You could get around that problem with a nested array, but it is *still*
not a good idea.
If felt the need to anything, I would add a helper method that ensures
pairing:
enum Thing {
T1,...;
private static void createMate(Map<Thing, Thing> matesMap,
Thing a, Thing b) {
assert null == matesMap.put(a, b);
assert null == matesMap.put(b, a);
}
... rest of original code, utilizing createMate.
}
This would do two things. If you only use createMate to add mates, you
are guaranteed that every relationship is reciprocal, and that you don't
accidentally mate one Thing with two others. Now, if you really wanted
to externalize this, and/or allowing the pairs to be configurable by
your end user, you can have your static block load a properties file
where the name/value pairs are T1=T2. use createMate(Thing.valueOf(key),
Thing.valueOf(value)); Although by that time, I would consider a
non-enum approach.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>