Java Reference
In-Depth Information
We can easily achieve this by changing the showAll method so that it returns a string
containing all command words instead of printing them out directly. (We should probably
rename it getCommandList when we make this change.) This string can then be printed in the
printHelp method in Game .
Note that this does not gain us anything right now, but we might profit from the improved
design in the future.
Exercise 6.18 Implement the suggested change. Make sure that your program still works
as before.
Exercise 6.19 Find out what the model-view-controller pattern is. You can do a web search
to get information, or you can use any other sources you find. How is it related to the topic
discussed here? What does it suggest? How could it be applied to this project? (Only discuss
its application to this project, as an actual implementation would be an advanced-challenge
We introduced the idea of cohesion in Section 6.3: a unit of code should always be responsible
for one, and only one, task. We shall now investigate the cohesion principle in more depth and
analyze some examples.
The principle of cohesion can be applied to classes and methods: classes should display a high
degree of cohesion, and so should methods.
Cohesion of methods
When we talk about cohesion of methods, we seek to express the ideal that any one method
should be responsible for one, and only one, well-defined task.
Method cohesion.
A cohesive method
is responsible for
one, and only one,
well-defined task.
We can see an example of a cohesive method in the Game class. This class has a private method
named printWelcome to show the opening text, and this method is called when the game
starts in the play method (Code 6.8).
Code 6.8
Two methods with a
good degree of
* Main play routine. Loops until end of play.
public void play()
// Enter the main command loop. Here we repeatedly read
// commands and execute them until the game is over.
Search WWH ::

Custom Search