Java Magazine, March/April 2016
ORACLE COM JAVAMAGAZINE MARCH APRIL 2016 41 new to java break An alternative would be to define a sequence of int constants for these commands and then translate the input string to a number and switch on the int constant This popular variant has the same problems that I discuss with our solution here Whats wrong with this solution There are really two separate fundamental problems that immediately stand out type safety and internationalization Lets deal with type safety first The short code segment presented above is quite straightforward and easy to understand It works right In fact it doesnt There is a bug in the code Did you spot it The problem is that the help command has been mistyped in the switch statement as Help Even though it was our intention that the commandWord should only ever be one of the strings listed as valid commands there is nothing stopping us from assigning invalid commands or comparing it to invalid commands Because the declared type is String any string will do In efect our type system is not good enough The declared type does not properly describe the set of acceptable values and logically illegal values can be used without the type system being able to detect this Enums to the Rescue To avoid this problem we can rewrite our code using enums We first write an enum declaration public enum CommandWord GO LOOK TAKE HELP QUIT This declaration should be treated like a class and written in its own file It defines the type CommandWord and the five listed names as valid values for that type In other classes we can then declare variables of this type and assign values For example CommandWord command CommandWord GO And importantly we can rewrite our switch statement to the following switch commandWord case GO goRoom secondWord break case LOOK look break case TAKE takeItem secondWord break case HELP printHelp break case QUIT quit break The definition of the command words in this version as an enum instead of a string array is not only clearer and simpler it also creates type safety if you now mistype a case label or a value in an assignment the compiler will detect this and notify you This is a real win we have our strong type system back that Java was designed for By the way we can also use the double equals symbol for checking equality instead of the equals method that we had to use with strings if command CommandWord QUIT
You must have JavaScript enabled to view digital editions.