Java Reference
In-Depth Information
We should be prepared to factor out methods (turn a sequence of statements from the body of
an existing method into a new, independent method) and classes (take parts of a class and create
a new class from it). Considering refactoring regularly keeps our class design clean and saves
work in the end. Of course, one of the things that will actually mean that refactoring makes life
harder in the long run is if we fail to adequately test the refactored version against the original.
Whenever we embark on a major refactoring task, it is essential to ensure that we test well,
before and after the change. Doing these tests manually (by creating and testing objects interac-
tively) will get tedious very quickly. We shall investigate how we can improve our testing—by
automating it—in the next chapter.
Exercise 6.28 Refactor your project to introduce a separate Player class. A Player
object should store at least the current room of the player, but you may also like to store the
player's name or other information.
Exercise 6.29 Implement an extension that allows a player to pick up one single item. This
includes implementing two new commands: take and drop .
Exercise 6.30 Extend your implementation to allow the player to carry any number of
items.
Exercise 6.31 Add a restriction that allows the player to carry items only up to a specified
maximum weight. The maximum weight a player can carry is an attribute of the player.
Exercise 6.32 Implement an items command that prints out all items currently carried and
their total weight.
Exercise 6.33 Add a magic cookie item to a room. Add an eat cookie command. If a player
finds and eats the magic cookie, it increases the weight that the player can carry. (You might
like to modify this slightly to better fit into your own game scenario.)
6.13
Refactoring for language independence
One feature of the z uul game that we have not commented on yet is that the user interface is closely
tied to commands written in English. This assumption is embedded in both the CommandWords
class, where the list of valid commands is stored, and the Game class, where the processCom-
mand method explicitly compares each command word against a set of English words. If we wish
to change the interface to allow users to use a different language, then we would have to find all
the places in the source code where command words are used and change them. This is a further
example of a form of implicit coupling, which we discussed in Section 6.9.
If we want to have language independence in the program, then ideally we should have just one place
in the source code where the actual text of command words is stored and have everywhere else refer to
commands in a language-independent way. A programming language feature that makes this possible
is enumerated types , or enums. We will explore this feature of Java via the zuul-with-enums projects.
 
 
Search WWH ::




Custom Search