Java Reference
In-Depth Information
This approach, however, does not display a good degree of cohesion: the Room class now de-
scribes both a room and an item. It also suggests that an item is bound to a particular room,
which we might not wish to be the case.
A better design would create a separate class for items, probably called Item . This class would have
fields for a description and weight, and a room would simply hold a reference to an item object.
Exercise 6.20 Extend either your adventure project or the zuul-better project so that a room
can contain a single item. Items have a description and a weight. When creating rooms and
setting their exits, items for this game should also be created. When a player enters a room,
information about an item present in this room should be displayed.
Exercise 6.21 How should the information be produced about an item present in a room?
Which class should produce the string describing the item? Which class should print it?
Why?  Explain in writing. If answering this exercise makes you feel you should change your
implementation, go ahead and make the changes.
The real benefits of separating rooms and items in the design can be seen if we change the
specification a little. In a further variation of our game, we want to allow not only a single item
in each room, but an unlimited number of items. In the design using a separate Item class, this
is easy: we can create multiple Item objects and store them in a collection of items in the room.
With the first, naïve approach, this change would be almost impossible to implement.
Exercise 6.22 Modify the project so that a room can hold any number of items. Use a
collection to do this. Make sure the room has an addItem method that places an item into the
room. Make sure all items get shown when a player enters a room.
6.11.3
Cohesion for readability
There are several ways in which high cohesion benefits a design. The two most important ones
are readability and reuse .
The example discussed in Section 6.11.1, cohesion of the printWelcome method, is clearly an
example in which increasing cohesion makes a class more readable and thus easier to under-
stand and maintain.
The class-cohesion example in Section 6.11.2 also has an element of readability. If a separate Item
class exists, a maintenance programmer will easily recognize where to start reading code if a change
to the characteristics of an item is needed. Cohesion of classes also increases readability of a program.
6.11.4
Cohesion for reuse
The second great advantage of cohesion is a higher potential for reuse.
The class-cohesion example in Section 6.11.2 also shows an example of this: by creating a separate
Item class, we can create multiple items and thus use the same code for more than a single item.
 
Search WWH ::




Custom Search