Need help extrapolating Java code
- by Berlioz
If anyone familiar with Rebecca Wirfs-Brock, she has a piece of Java code found in her book titled, Object Design: Roles, Responsibilities, and Collaborations.
Here is the quote Applying Double Dispatch to a Specific Problem
To implement the game Rock, Paper, Scissors we need to write code that determines whether
one object “beats” another. The game has nine possible outcomes based on the three kinds of
objects. The number of interactions is the cross product of the kinds of objects. Case or switch statements are often governed by the type of data that is being operated on. The
object-oriented language equivalent is to base its actions on the class of some other object. In Java,
it looks like this
Here is the piece of Java code on page 16 '
import java.util.*;
import java.lang.*;
public class Rock
{
public static void main(String args[])
{
}
public static boolean beats(GameObject object)
{
if (object.getClass.getName().equals("Rock"))
{
result = false;
}
else if (object.getClass.getName().equals("Paper"))
{
result = false;
}
else if(object.getClass.getName().equals("Scissors"))
{
result = true;
}
return result;
}
}'
===This is not a very good solution. First, the receiver needs to know too much about the argument.
Second, there is one of these nested conditional statements in each of the three classes. If new
kinds of objects could be added to the game, each of the three classes would have to be modified.
Can anyone share with me how to get this "less than optimal" piece of code to work in order to see it 'working'. She proceeds to demonstrate a better way, but I will spare you.
Thanks