Contents
Are enums bad?
It provides strong type safety. They have some disadvantages at times, but this is really typically related to situations where every possible option is not known in advance. If you have a fixed set of options, such as your example, then strong typed enums are a good thing, and should not be avoided.
Are enums immutable?
Java enums are tightly immutable, so it makes sense that the enum must return a clone of the array returned by the values() method each time that method is called to ensure that the array associated with the enum is not changed.
Are enums good?
Enums provide readability and flexibility over a class with constants. Few other advantages that I can think of enum types. They is always one instance of a particular enum class (hence the concept of using enums as singleton arrives). Another advantage is you can use enums as a type in switch-case statement.
Do enums save memory?
The GCC C compiler will allocate enough memory for an enum to hold any of the values that you have declared. So, if your code only uses values below 256, your enum should be 8 bits wide. If you store enums in non-volatile memory or on disk, be sure to review any code that might need to be updated when the size changes.
How are enums stored in memory Java?
In Java, there should only be one instance of each of the values of your enum in memory. A reference to the enum then requires only the storage for that reference. Checking the value of an enum is as efficient as any other reference comparison. You would only worry about this when storing large quantities of enums.
Why are enums not always the best option?
Since the books you refer to deal with the object-oriented paradigm, it is not surprising that they are biased against using enums. However, an object-orientation solution is not always the best option. Bottomline: enums are not necessarily a code smell.
When is transmitting data using enums is no code smell?
When transmitting data enums are no code smell. IMHO, when transmitting data using enums to indicate that a field can have a value from a restricted (seldom changing) set of values is good. I consider it preferable to transmitting arbitrary strings or ints. Strings may cause problems by variations in spelling and capitalisation.
How to store a bitwise combination of enums?
Use a plain integer if you want to store a bitwise combination of enums: But this would reduce everything to an int, leaving you with no clue as to which type you’re supposed to put in the method. Write a separate class that will overload operators and hold the bitwise flags in a hidden integer field:
What does it mean when enum smells like something?
Firstly, a code-smell doesn’t mean that something is wrong. It means that something might be wrong. enum smells because its frequently abused, but that doesn’t mean that you have to avoid them. Just you find yourself typing enum, stop and check for better solutions.