Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use Enums instead of Constants? Which is better in terms of software design and readability

I have a scenario in which I have Player types ARCHER,WARRIOR, and sorcerer.
What should I use in Player class for a player type?
Constant final static String variable or an Enum? and Why?
Please help with reasons.

like image 619
Waqas Avatar asked Jul 20 '12 08:07

Waqas


People also ask

Why are enums better?

Advantages of enum: enum improves type safety at compile-time checking to avoid errors at run-time. enum can be easily used in switch. enum can be traversed. enum can have fields, constructors and methods.

When should we use an enum over a regular constant variable?

Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.

What is the difference between enum and constant?

The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Why do we use enums in programming?

Enums are used when we know all possible values at compile-time, such as choices on a menu, rounding modes, command-line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time. In Java (from 1.5), enums are represented using enum data type.


1 Answers

Suppose you use constant strings (or int values - the same goes for them):

// Constants for player types public static final String ARCHER = "Archer"; public static final String WARRIOR = "Warrior";  // Constants for genders public static final String MALE = "Male"; public static final String FEMALE = "Female"; 

then you end up not really knowing the type of your data - leading to potentially incorrect code:

String playerType = Constants.MALE; 

If you use enums, that would end up as:

// Compile-time error - incompatible types! PlayerType playerType = Gender.MALE; 

Likewise, enums give a restricted set of values:

String playerType = "Fred"; // Hang on, that's not one we know about... 

vs

PlayerType playerType = "Fred"; // Nope, that doesn't work. Bang! 

Additionally, enums in Java can have more information associated with them, and can also have behaviour. Much better all round.

like image 162
Jon Skeet Avatar answered Oct 13 '22 06:10

Jon Skeet