Java Reference
In-Depth Information
Code 6.8
continued
Two methods with a
good degree of
cohesion
boolean finished = false ;
while (! finished) {
Command command = parser.getCommand();
finished = processCommand(command);
}
System.out.println( "Thank you for playing. Good bye." );
}
/**
* Print out the opening message for the player.
*/
private void printWelcome()
{
System.out.println();
System.out.println( "Welcome to The World of Zuul!" );
System.out.println(
"Zuul is a new, incredibly boring adventure game." );
System.out.println( "Type 'help' if you need help." );
System.out.println();
System.out.println(currentRoom.getLongDescription());
}
From a functional point of view, we could have just entered the statements from the print-
Welcome method directly into the play method and achieved the same result without defining
an extra method and making a method call. The same can, by the way, be said for the pro-
cessCommand method that is also invoked in the play method: this code, too, could have been
written directly into the play method.
It is, however, much easier to understand what a segment of code does and to make modifi-
cations if short, cohesive methods are used. In the chosen method structure, all methods are
reasonably short and easy to understand, and their names indicate their purposes quite clearly.
These characteristics represent valuable help for a maintenance programmer.
6.11.2
Cohesion of classes
The rule of cohesion of classes states that each class should represent one single, well-defined
entity in the problem domain.
Concept:
Class cohesion
A cohesive class
represents one
well-defined entity.
As an example of class cohesion, we now discuss another extension to the zuul project. We now
want to add items to the game. Each room may hold an item, and each item has a description and
a weight. An item's weight can be used later to determine whether it can be picked up or not.
A naïve approach would be to add two fields to the Room class: itemDescription and item-
Weight . This could work. We could now specify the item details for each room, and we could
print out the details whenever we enter a room.
 
Search WWH ::




Custom Search