Re: enum or array ?
news.t-com.hr wrote:
Is it better to define some constants this way and what are pros and cons ?
String[] currency = {"US","EUR"....};
or to do this
public enum CURRENCY{
CURR1("US"),
CURR2("EUR")....
;
String currency ;
public CURRENCY(String tmp){
currency = tmp;
}
public getCurrency(){
return currency;
}
}
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. So let's suppose your class has lots
of super-nifty methods that use Currency objects, taking them as
arguments and returning them as results and doing lots of neat stuff.
Wonderful! I'd like to use your class -- but unfortunately, I need
to work with the Flanian Pobble Bead and the Elbonian Grubnick in
addition to the currencies you've defined. Can I do it? No![*]
I could define my own Currency enum with a wider repertoire, but it
wouldn't be compatible with yours and your methods wouldn't accept
or return it.
To get the benefits of your class, I'd have to copy the source of
the whole thing (assuming I can get it and assuming you allow copying),
add my extra currencies to my copy of the Currency enum, and plunge
ahead with a redundant copy. This technique is known as "code re-use
by copy-and-paste," and deserves its bad reputation. The greatest
drawback, IMHO, is that if you fix a bug in your class or make an
improvement to it, my bastardized copy still has the old buggy or
inferior behavior. And all because you decided to make the universe
of Currency instances unchangeable ...
[*] If I'm wrong about this, I'd *love* to be corrected. Please?
--
Eric.Sosman@sun.com