enum or array ?

N

news.t-com.hr

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;
}

}



__________ Information from ESET NOD32 Antivirus, version of virus signature database 4096 (20090522) __________

The message was checked by ESET NOD32 Antivirus.

http://www.eset.com
 
L

Lew

news.t-com.hr said:
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{

'enum' is better.

BTW, the convention for class names is mixed (camel) case, with the first
letter capitalized, thus, "Currency".
CURR1("US"),
CURR2("EUR")....

Please follow indentation conventions.
;

String currency ;

public CURRENCY(String tmp){

currency = tmp;
}
public getCurrency(){

Also, it often pays to override 'toString()' to return the custom string
representation.
return currency;
}

}

'enum' is better - you get the compiler's cooperation to make sure you are
using correct values. You can 'switch()' on it. You can define behaviors on it.

Use more meaningful enum names, though, like 'US', 'EUR', etc.
 
M

Mike Schilling

Lew said:
news.t-com.hr said:
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{

'enum' is better.

BTW, the convention for class names is mixed (camel) case, with the
first letter capitalized, thus, "Currency".
CURR1("US"),
CURR2("EUR")....

Please follow indentation conventions.
;

String currency ;

public CURRENCY(String tmp){

currency = tmp;
}
public getCurrency(){

Also, it often pays to override 'toString()' to return the custom
string representation.
return currency;
}

}

'enum' is better - you get the compiler's cooperation to make sure
you are using correct values. You can 'switch()' on it. You can
define
behaviors on it.

You can use "==" instead of ".equals()" to compare them.

You can deal with any casing issues in one place (where you convert a
user-entered string to an enum), and not worry about them anywhere
else.
 
M

Mark Space

news.t-com.hr said:
public enum CURRENCY{

CURR1("US"),
CURR2("EUR")....

enum is better although this would be better as:

public enum Currency { US, EUR, ... }

Use Sun's coding conventions for capitalization: Class names start with
a capital letter ("Currency"), constants are all upper case.

If you need more information, say a long and short form of currency
description, then your method is preferred.

Except for the xx1, xx2, xx3, part. Don't do that, give the enums
descriptive names, even if you don't think you'll use them. They show
up really well in debugging and serialization. You'll be happy you did
later, I guarantee it.
 
S

Seamus MacRae

Lew said:
'enum' is better.
Ding!

BTW, the convention for class names is mixed (camel) case, with the
first letter capitalized, thus, "Currency".
[X]

Please follow indentation conventions.
[X][X]

Also, it often pays to override 'toString()' to return the custom string
representation.

Ding! Ding!
'enum' is better - you get the compiler's cooperation to make sure you
are using correct values. You can 'switch()' on it. You can define
behaviors on it.
DingDingDing!

Use more meaningful enum names, though, like 'US', 'EUR', etc.

[X][X][X]

Hey, fully 50% relevant to OP's question and only 50% unsolicited
grammar/style flames. Lew, you must be slipping. (FWIW, I don't disagree
with the content of the style flames, and would probably have suggested
more meaningful enum names myself.)
 
A

Albert

news.t-com.hr a écrit :
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;
}

}

Use enum for these reason:
- you can use the enum type in parameters or fields declarations
- don't use name() in IO if you want to refactor enum constants later
- keep string or int constant with each enum constant like in your example
 
M

Mark Space

Eric said:
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.
 
R

Roedy Green

Is it better to define some constants this way and what are pros and cons ?

String[] currency = {"US","EUR"....};

enums have the advantage:
1. can use in case statements
2. built in code to lookup name, convert to ordinal, do combos with
EnumSet.
3. can attach code to different enum constants.

Arrays have the advantage:
1. can add new values without recompile.
2. lighter weight. No extra class needed.
--
Roedy Green Canadian Mind Products
http://mindprod.com

"Everybody’s worried about stopping terrorism. Well, there’s a really easy way: stop participating in it."
~ Noam Chomsky
 
M

Mike Schilling

Mark said:
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.

That's true. But it's quite possible (i.e. I've done it) to build a
class that mimics the code generated for Enums while allowing both
predefined values (which get static instances generated for them) plus
values added at runtime (which do not.) (In fact, since the Java
code for such a class is boilerplate, I've built a tool to generate
it.) You still get many of the advantages of enums, but not all: e.g.
you can't switch on them, nor can you override methods per-value.
 
R

Roedy Green

Hey, fully 50% relevant to OP's question and only 50% unsolicited
grammar/style flames

Hey. Its his tick, a sort of stutter. It is a bit like the way some
people can't get out a sentence without the word "fucking" inserted
every place an adjective could theoretically go.

Unfortunately, newcomers might take the dressing down seriously and
feel unwelcome and leave. What Lew could do, which would not be quite
so abrasive? He could insert [sic] after every error, or quietly
CORRECT all the errors.

People learn to pronounce and spell incorrectly by imitation. Ditto
for doing it correctly.

I am disturbed that the Texan pronunciation of "to"/"ta" and
"water"/"wadder" is invading Canada. I consider it fair game to
correct professional announcers, but not casual acquaintances.
--
Roedy Green Canadian Mind Products
http://mindprod.com

"Everybody’s worried about stopping terrorism. Well, there’s a really easy way: stop participating in it."
~ Noam Chomsky
 
L

Lew

Seamus MacRae said :
It was all relevant.

Roedy said:
Hey. Its his tick, a sort of stutter. It is a bit like the way some
people can't get out a sentence without the word "fucking" inserted
every place an adjective could theoretically go.

Oh, yeah, it's just like that.

Not.
Unfortunately, newcomers might take the dressing down seriously and

There was no "dressing down". I gave hints as to the well-established
conventions for Java names. At no point did I express any criticism; I only
offered correct information.

Or do you claim that camel case with an upper-case first letter is not the
convention for type names in Java?
feel unwelcome and leave. What Lew could do, which would not be quite
so abrasive? He could insert [sic] after every error, or quietly
CORRECT all the errors.

Abrasiveness is in the eye of the beholder. For example, I find your /ad
hominem/ style somewhat abrasive, in particular, you refer to "errors" that I
did not name as such. I only spoke of conventions, things that will help the
OP, and of technical matters such as the benefits of overriding 'toString()'
or using meaningful constant names.
People learn to pronounce and spell incorrectly by imitation. Ditto
for doing it correctly.

They also learn when someone takes the trouble to explain things explicitly
instead of leaving the poor, hapless newbie to flounder, wondering exactly
what is important and what isn't.
I am disturbed that the Texan pronunciation of "to"/"ta" and
"water"/"wadder" is invading Canada. I consider it fair game to
correct professional announcers, but not casual acquaintances.

I consider it fair game to introduce people explicitly to good practice, and
not make them dangle wondering in some perverted mind game of "do as I do, not
as I say". That you see fit to criticize my character instead of to address
the actual technical points in my post, none of which were criticisms, is
telling as to the merits of your position.
 
L

Lew

Mark said:
Use Sun's coding conventions for capitalization: Class names start with
a capital letter ("Currency"), constants are all upper case.

Be careful, Mark Space, lest someone criticize you for "dressing down" the OP.
 
L

Lew

Roedy said:
Is it better to define some constants this way and what are pros and cons ?

String[] currency = {"US","EUR"....};

enums have the advantage:
1. can use in case statements
2. built in code to lookup name, convert to ordinal, do combos with
EnumSet.
3. can attach code to different enum constants.

Arrays have the advantage:
1. can add new values without recompile.
2. lighter weight. No extra class needed.

The difference in weight between an array of values and an enum is very, very
slight, especially measured against the benefits of type safety, grammatical
flexibility and notational convenience of enums.
 
S

Seamus MacRae

Lew said:
It was all relevant.

No, the OP never requested a stylistic criticism.
There was no "dressing down". I gave hints as to the well-established
conventions for Java names.

Yeah, "hints". How do you hint when you want someone to go away? With a
baseball bat?
At no point did I express any criticism

Ridiculous. You certainly implied plenty.
Or do you claim that camel case with an upper-case first letter is not
the convention for type names in Java?

I made no claim about the convention.
feel unwelcome and leave. What Lew could do, which would not be quite
so abrasive? He could insert [sic] after every error, or quietly
CORRECT all the errors.

Abrasiveness is in the eye of the beholder.

It seems that yours is in the eye of many a beholder.
For example, I find your /ad hominem/ style somewhat abrasive

Irony detected.
They also learn when someone takes the trouble to explain things
explicitly instead of leaving the poor, hapless newbie to flounder,
wondering exactly what is important and what isn't.

So rather than leave the "poor, hapless newbie to flounder" you kick it
back into the sea with the steel-toed tip of a hobnail boot?
I consider it fair game to introduce people explicitly to good practice,
and not make them dangle wondering in some perverted mind game of "do as
I do, not as I say". That you see fit to criticize my character instead
of to address the actual technical points in my post, none of which were
criticisms, is telling as to the merits of your position.

Says he who responds fairly often to a post with either a
foaming-at-the-mouth over-the-top flame or, at the very least, several
insinuations that the other guy is a liar. Giovanni was on the receiving
end of several such attacks. A few months back, around December, some
Santa Claus wannabe got toasted and you implied he was Satan! You also
slung quite a bit of mud in that Lisp thread, some of it at me. That I
don't quickly forget, which is why I now react when you say something
hypocritical elsewhere.
 
J

Joshua Cranmer

Seamus said:
So rather than leave the "poor, hapless newbie to flounder" you kick it
back into the sea with the steel-toed tip of a hobnail boot?

Think of the poor OP whose thread is now in the middle of a flamewar!
 
R

Roedy Green

Yeah, "hints". How do you hint when you want someone to go away? With a
baseball bat?

I find it odd that Lew does not yet understand he is bully. Perhaps
having several people call him on it will make him reevaluate.

The religious fundamentalists used shunning to non-violently enforce
conformant behaviour. We netizens have the plonk or temporary plonk
to make someone all but disappear from your universe without doing
them violence.

Newbies don't realise they have that same power, and that newsgroup
bullies cannot physically hurt them. Newbies cower from bullies
reflexively as they did from groups of large bullies in school days.
They just take the abuse or slink away.

Given than I consider one of my most important life purposes is to
encourage newbies from the third world to learn computer programming,
I make it my personal business to harass newsgroup bullies.

I am not asking Lew to stop making even the most picky corrections,
just to cut the put downs that go with them. Nearly everyone learns to
walk. Criticising, shouting and berating would not help a child learn
to walk any faster. It won't help adults either. It is even more
counter productive since adults are far more terrified of making a
mistake than are children. The problem is encouraging them to
experiment more and make MORE mistakes.


--
Roedy Green Canadian Mind Products
http://mindprod.com

"Everybody’s worried about stopping terrorism. Well, there’s a really easy way: stop participating in it."
~ Noam Chomsky
 
L

Lew

Roedy said:
I am not asking Lew to stop making even the most picky corrections,
just to cut the put downs that go with them. Nearly everyone learns to

What "put-downs"?

You are the bully, here.
walk. Criticising, shouting and berating would not help a child learn
to walk any faster. It won't help adults either. It is even more
counter productive since adults are far more terrified of making a
mistake than are children. The problem is encouraging them to
experiment more and make MORE mistakes.

And yet you are criticizing and berating.

Plonk, Roedy, you troll.
 
L

Lew

Sabine said:
You can define for example (not tested code)

public enum Currency {
USD ("USD",840,2,"US dollar"),
// etc

private String code;
private int num;
private int decimals;
private String currency;

You're likely better off making these variables 'final'.
Currency(String curCode, int curNum, int curDec, String currency) {
this.code = curCode;
this.num = curNum;
this.decimals = curDec;
this.currency = currency;
}

@Override
public String toString() {
return this.code;
}

// etc methods to return the other values
}

Use more meaningful enum names, though, like 'US', 'EUR', etc.

I'd say use the ISO currency codes [1] while you're at it.

[1]<http://www.xe.com/iso4217.php>
<http://en.wikipedia.org/wiki/ISO_4217>

Excellent advice.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top