Java Magazine, March/April 2016
ORACLE COM JAVAMAGAZINE MARCH APRIL 2016 40 new to java Enumerations or enums for short are Java constructs that are not used as much as they should be They arent one of those big bold buzzy concepts that get people excited or force themselves on you Rather they quietly improve code making it more reliable and more readable If youre new to Java then its entirely possible that youre writing good functioning code but are not using enums If so youre not alone There are several reasons why some developers dont use them First early versions of Java did not have enums Some programmers may have learned Java before Java 5 when enums were added to the language and they never got around to changing their habits Others may have come from different languages that did not support enums And lastly you might not have felt the need to use them because you were perfectly able to solve your problems without them None of these are good reasons to continue ignoring them Enums enable you to make your code significantly better more robust more type safe less error prone and more elegant And these things matter So sit back and read on When and Why to Use Enums Lets examine the use of enums with an example Suppose you want to write a text based adventure game something similar to Colossal Cave Adventure or Zork two classic computer games Then you will have a set of command words that the user can type in And lets say the valid command words are go look take help and quit Somewhere in your code you are likely to have a definition of those command words In a straightforward first implementation they might be defined in an array of strings like this private static final String validCommands go look take help quit Somewhere else in your program you will have some code that reacts to these words being entered The code then calls the right method to act on them In this code snippet I assume that the String variable commandWord holds the word that was typed in switch commandWord case go goRoom secondWord break case look look break case take takeItem secondWord break case Help printHelp break case quit quit MICHAEL KÖLLING PHOTOGRAPH BY JOHN BLYTHE Making the Most of Enums Anytime you have a set of known constant values an enum is a type safe representation that prevents common problems
You must have JavaScript enabled to view digital editions.