Java Reference
In-Depth Information
With the text of the commands stored in the
CommandWord
type, the
CommandWords
class in
zuul-with-enums-v2
uses a different way to create its map between text and enumerated values:
validCommands = new HashMap<String, CommandWord>();
for(CommandWord command : CommandWord.values()) {
if(command != CommandWord.UNKNOWN) {
validCommands.put(command.toString(), command);
}
}
Every enumerated type defines a
values
method that returns an array filled with the value
objects from the type. The code above iterates over the array and calls the
toString
method to
obtain the command
String
associated with each value.
Exercise 6.39
Add your own
look
command to
zuul-with-enums-v2
. Do you only need to
change the
CommandWord
type?
Exercise 6.40
Change the word associated with the
help
command in
CommandWord
. Is
this change automatically reflected in the welcome text when you start the game? Take a look
at the
printWelcome
method in the
Game
class to see how this has been achieved.
6.14
Design guidelines
An often-heard piece of advice to beginners about writing good object-oriented programs is,
“Don't put too much into a single method” or “Don't put everything into one class.” Both sug-
gestions have merit but frequently lead to the counter-questions, “How long should a method
be?” or “How long should a class be?”
After the discussion in this chapter, these questions can now be answered in terms of cohesion
and coupling. A method is too long if it does more than one logical task. A class is too complex
if it represents more than one logical entity.
You will notice that these answers do not give clear-cut rules that specify exactly what to do.
Terms such as
one logical task
are still open to interpretation, and different programmers will
decide differently in many situations.
These are
guidelines
(not cast-in-stone rules). Keeping these in mind, though, will significantly
improve your class design and enable you to master more complex problems and write better
and more interesting programs.
It is important to understand the following exercises as suggestions, not as fixed specifica-
tions. This game has many possible ways in which it can be extended, and you are encour-
aged to invent your own extensions. You do not need to do all the exercises here to create an
interesting game; you may want to do more, or you may want to do different ones. Here are
some suggestions to get you started.
Search WWH ::
Custom Search