4Matt
4Matt

Reputation: 251

Importance of Enums

I am a little bit confused on why Enums are important. Lets say we have the following code...

enum playerState {walking, running, idle, jumping, dead};

playerState myPlayerState = idle;

if{energy == 0}
{
  myPlayerState = dead;
}

How is this more efficient than just using a string and avoiding the enumeration altogether, and switching to new appropriate string values when necessary?

string playerState = "idle";

if{energy == 0}
{
  playerState = "dead";
}

Upvotes: 2

Views: 492

Answers (3)

Carcigenicate
Carcigenicate

Reputation: 45740

The difference is an Enum defines a strict set of values that a variable can hold, and will give you a compile-time error if you try to give it something bad.

With Strings, they can take any value, and if the string is "bad" by some definition in your program, it will fail at runtime instead; or not at all, and lead to unpredictable behaviour.

Things failing at compile time are much better than them failing at runtime; when possible.

@Jeff is right too though. An Enum will take up less space pretty much always, so if you have a lot of variables floating around, using an Enum may make a difference.

Upvotes: 3

SorMun
SorMun

Reputation: 105

  1. The Enum type is in most languages a restricted integer (an integer that can take a set a set of finite values) that is known to the compiler and can be checked at compile time
  2. Since the finite values of an Enum have human readable names it makes the code more readable
  3. Unlike the strings, the storage and manipulation of Enums require less computational effort
  4. Most of the code editors will have some sort of IntelliSense that will allow a the coder to select one of the possible values, thus making the code more writeable

Upvotes: 1

jeff carey
jeff carey

Reputation: 2373

2 reasons:

1) In most languages the enum will be implemented using an integer or similar, which typically will take up less memory than a comparable string.

2) It is a guide for other developers looking at your code, letting them know that there is a finite list of possible states the variable can take on, and telling them what they are in natural language.

Upvotes: 2

Related Questions