After reading some questions and answers about enum I don't find it really useful...
It's something between class and a variable but I know where can I use it so it would be more useful then a class, or a couple of variables for example.
CA1069: Enums should not have duplicate values.
The benefits of using enumerations include: Reduces errors caused by transposing or mistyping numbers. Makes it easy to change values in the future. Makes code easier to read, which means it is less likely that errors will creep into it.
Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.
Enums limit you to the required set of inputs whereas even if you use constant strings you still can use other String not part of your logic. This helps you to not make a mistake, to enter something out of the domain, while entering data and also improves the program readability.
There are other things you can do and reasons to use them, but the primary reason I use enums is to prevent the possibility of an invalid parameter. For example, imagine the following method:
public void doSomethingWithAMonth(int monthNum);
This is not only ambiguous (do month indexes start at 1, or at 0?), but you can give down-right invalid data (13+, negative numbers). If you have an enum Month
with JAN, FEB, etc. the signature becomes:
public void doSomethignWithAMonth(Month month);
Code calling this method will be far more readable, and can't provide invalid data.
I use Enums for anything that has multiple nonchanging "type" of something. i.e days of a week.
Why I don't use String in this case is because I can't do switch statement on the String and I can on Enum so for every day of a week I can do something specific.
I also use Enum when working with singleton pattern, Check the Effective Java book CH2(CHAPTER 2 CREATING AND DESTROYING OBJECTS), quote :
"While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton." not gonna paste code read the book it's excellent.
If I were you I'd firstly read Thinking in java chapter Enumerated Types. Then after that Effective Java chapter 6 and you should be good
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With