Java Reference
In-Depth Information
if(currentRoom.westExit != null) {
System.out.print("west ");
}
System.out.println();
Code duplication is usually a symptom of bad cohesion. The problem here has its roots in the
fact that both methods in question do two things:
printWelcome
prints the welcome message
and prints the information about the current location, while
goRoom
changes the current loca-
tion and then prints information about the (new) current location.
Both methods print information about the current location, but neither can call the other,
because they also do other things. This is bad design.
A better design would use a separate, more cohesive method whose sole task is to print the cur-
rent location information (Code 6.2). Both the
printWelcome
and
goRoom
methods can then
make calls to this method when they need to print this information. This way, writing the code
twice is avoided, and when we need to change it, we need to change it only once.
Code 6.2
printLocation
Info
as a separate
method
private
void
printLocationInfo()
{
System.out.println(
"You are "
+ currentRoom.getDescription());
System.out.print(
"Exits: "
);
if
(currentRoom.northExit !=
null
) {
System.out.print(
"north "
);
}
if
(currentRoom.eastExit !=
null
) {
System.out.print(
"east "
);
}
if
(currentRoom.southExit !=
null
) {
System.out.print(
"south "
);
}
if
(currentRoom.westExit !=
null
) {
System.out.print(
"west "
);
}
System.out.println();
}
Exercise 6.5
Implement and use a separate
printLocationInfo
method in your
project, as discussed in this section. Test your changes.
6.5
Making extensions
The
zuul-bad
project does work. We can execute it, and it correctly does everything that it was
intended to do. However, it is in some respects quite badly designed. A well-designed alterna-
tive would perform in the same way; we would not notice any difference just by executing the
program.
Search WWH ::
Custom Search