Re: enum or array ?
Eric Sosman wrote:
Others have mentioned some "pros" of enums; I'll mention a "con"
for the sake of balance (and because I'm a contrary sort of guy).
The con-stants of an enum are fixed at compile time and cannot be
changed without recompilation.
This is a good point. If the OP is defining a set of parameters that
his classes accept, then I think that's appropriate use of Enum. If
he's designing something that at all that reflects the need to alter as
the real world -- or some other system -- itself changes, then I agree.
Enums are limiting in this regard.
In the "real world enumeration" case, I think it's better to think in
terms of "data driven design" and similar strategies. Think how much
easier it would be if to add more currency all you have to do is modify
a simple data properties file:
#Property: short name, long name, conversion
my.stuff.currency.US: US, U.S. Dollar, 1.43
my.stuff.currency.EUR: EUR, Euro, 1.00
my.stuff.currency.YUAN: YN, Chinese Yuan, 0.14
This is much easier to maintain, as you can push work off to the
maintainer, and you don't have to recompile any code.
[*] If I'm wrong about this, I'd *love* to be corrected. Please?
You know about the interface trick?
public interface Currency {
String shortName();
String longName();
float conversion();
}
public enum MyCurrency implements Currency {
US( "US", "US Dollar", 1.43f),
EUR( "EUR", "Euro", 1.0f),
...
;
private MyCurrency( String longName, String shortName,
float conversion ) {
....
}
...
}
Now to make a new enum, just define your own and implement the same
interface:
public enum YourCurrency implements Currency {
... etc
}
Method parameters have to take a type of Currency, not MyCurrency, or
Enum for this to work, but it does allow some extensibility. I do agree
however that it is not as flexible as a class structure designed for
inheritance and other extension.