If you use enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.īetween, overuse of enums might mean that your methods do too much (it’s often better to have several separate methods, rather than one method that takes several flags which modify what it does), but if you have to use flags or type codes, enums are the way to go. Examples would be things like type constants (contract status: “permanent”, “temp”, “apprentice”), or flags (“execute now”, “defer execution”). You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. The only difference is that enum constants are public, static and final (unchangeable - cannot be. These output values happens to be same in some cases according to the specification. In my case, instances of MyEnum acts as keys to a map which keys I want also to output to external target. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. An enum can, just like a class, have attributes and methods. Juvanis: notice that each enum instance has it own unique name so I dont consider it as a violation against the idioms of enums. For instance, in a chess game you could represent the different types of pieces as an enum: enum ChessPiece Įnums 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. If you want to convey the availability of such language-specific features, you could define your own stereotype «Java enum» that specializes the standard UML enumeration metamodel element. The compareTo() method compares the enum constants. But Java enums all specialize, which offer operations such as name() or class operations such as values(). Have you heard of Final keyword? It’s like that. The ordinal() method returns the position of an enum constant. Enums are lists of constants like unchangeable variables. String enums allow you to give a meaningful and readable value when your code runs, independent of the name of the enum member itself.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |