Java Reference
In-Depth Information
Reuse is also an important aspect of method cohesion. Consider a method in the
Room
class
with the following signature:
public Room leaveRoom(String direction)
This method could return the room in the given direction (so that it can be used as the new
currentRoom
) and also print out the description of the new room that we just entered.
This seems like a possible design, and it can indeed be made to work. In our version, however,
we have separated this task into two methods:
public Room getExit(String direction)
public String getLongDescription()
The first one is responsible for returning the next room, whereas the second one produces the
room's description.
The advantage of this design is that the separate tasks can be reused more easily. The
getLongDe-
scription
method, for example, is now used not only in the
goRoom
method, but also in
print-
Welcome
and the implementation of the
look
command. This is only possible because it displays a
high degree of cohesion. Reusing it would not be possible in the version with the
leaveRoom
method.
Exercise 6.23
Implement a
back
command. This command does not have a second word.
Entering the
back
command takes the player into the previous room he/she was in.
Exercise 6.24
Test your new command. Does it work as expected? Also test cases where
the command is used incorrectly. For example, what does your program do if a player types a
second word after the
back
command? Does it behave sensibly?
Exercise 6.25
What does your program do if you type “back” twice? Is this behavior sensible?
Exercise 6.26
Challenge exercise
Implement the
back
command so that using it repeatedly
takes you back several rooms, all the way to the beginning of the game if used often enough. Use a
Stack
to do this. (You may need to find out about stacks. Look at the Java library documentation.)
6.12
Refactoring
When designing applications, we should attempt to think ahead, anticipate possible changes in
the future, and create highly cohesive, loosely coupled classes and methods that make modifi-
cations easy. This is a noble goal, but of course we cannot always anticipate all future adapta-
tions, and it is not feasible to prepare for all possible extensions we can think of.
Concept:
Refactoring
is
the activity of
restructuring an
existing design to
maintain a good
class design when
the application
is modified or
extended.
This is why
refactoring
is important.
Refactoring is the activity of restructuring existing classes and methods to adapt them to
changed functionality and requirements. Often in the lifetime of an application, functionality is
gradually added. One common effect is that, as a side-effect of this, methods and classes slowly
grow in length.
Search WWH ::
Custom Search