Re: Initializing a Map in an Interface?
On 3/16/2010 2:39 PM, Rhino wrote:
[...]
Since the Map of web-safe Colors is effectively immutable - the 216
colors have been defined and there aren't going to be any additions or
deletions to the list - it seems reasonable to put them in a some kind
of permanent structure, like an Interface. But maybe there are better
options, like the Enum or EnumMap that someone suggeested elsewhere in
the thread. Or in a class.
An interface feels wrong for this. The primary purpose of
an interface is to be implemented by classes, to ensure that
the implementing classes provide methods with the right names
and signatures. Sometimes an interface defines constants, in
essence conveniences for the implementors and callers, but this
has now mostly been supplanted (and improved on) by Enums. A
few interfaces exist that specify no methods at all and merely
define constants; this is now viewed as Something We Did When
We Were Too Young To Know Any Better.
I'm not particularly wedded to putting the Map in an interface or even
to using a Map at all. I'm really just looking for a good way to
ensure that ColorSets can only contain specific values rather than any
old Color that can be defined in Java. That's the part of the problem
that interests me. I have no formal Java training so I'm just trying
to figure out a good way to ensure that a given group of somethings,
in this case a ColorSet, is always a subset of another set.
Putting a Map<String,Color> in an interface will not enforce
any such guarantee on the classes that implement it. Making an
`enum SafeColor' would be a first step, and then you could write
interfaces whose methods took SafeColor parameters and returned
SafeColor values (or List<SafeColor>, etc.). If the interface
specifies methods that return plain Colors, though, there's no
way to guarantee that the Colors come from your chosen few.
Another example of the same issue might be two-letter country codes.
Given that there is a list of recognized two-letter country codes,
'us' for United States, 'ca' for Canada, etc., how could I ensure that
a group of country codes - let's say, a list of North American
countries - only contains legitimate country codes like 'us' and 'ca'
and no non-existent codes, like 'xx'? (Unlike the web-safe colors, the
list of country codes is mutable as new countries, like Slovakia,
emerge and countries like the Soviet Union disappear. But you get the
idea.)
One way would be to have a Country class, with a static
method like `Country getCountryForCode(String countryCode)'.
The caller hands it a (supposed) country code, and it returns
the designated Country or null (or throws up, if you prefer).
I do not see how an interface would be of any help here.
--
Eric Sosman
esosman@ieee-dot-org.invalid