Need help extrapolating Java code
Posted
by Berlioz
on Stack Overflow
See other posts from Stack Overflow
or by Berlioz
Published on 2010-05-06T17:31:47Z
Indexed on
2010/05/06
17:38 UTC
Read the original article
Hit count: 210
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
© Stack Overflow or respective owner