aspose file tools*
The moose likes Beginning Java and the fly likes simple game - design choice - classes - accessing variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "simple game - design choice - classes - accessing variables" Watch "simple game - design choice - classes - accessing variables" New topic
Author

simple game - design choice - classes - accessing variables

daniel okeefe
Greenhorn

Joined: Nov 13, 2009
Posts: 4
Hi, quite new to OO and programming in general.
I'm trying to decide how to design a simple 3 (I think) class game.
Right now, 2 of my classes need to access the same variable ("rabbitNumber").
How do I do this without resorting to set/gets? Is there a way to not have to try to access variables between classes?
I want to stay on the encapsulation straight + narrow for as long as possible.

For background, this is a very simple NIM game, called, by some, POISON.
There are some objects (rabbits, in this version) and a poison. Players take turns taking either 1 or 2 objects (rabbits). The person left with the poison is poisoned of course.

The (simple) strategy (spoiler alert if you're into figuring it out) is to always leave your opponent w/ multiples of three. The AI is set up to do just that. I think. I can't compile and test though until I figure out what to do about passing, or not passing, the "rabbitNumber" variable. Thanks for any help.

Here's the code:

public class TigerStorm
{
public static void main(String[] args) {
GamePlay poison = new GamePlay();
poison.startGame();
}//end main
}//end class

public class GamePlay
{
public void startGame() {

boolean evilRabbit = false;
int deathNumber = 3;
int numberTaken;
Question questioning = new Question();
DeathNumberStrategy strategy = new DeathNumberStrategy();

while (evilRabbit == false)
{
questioning.question1();
strategy.deathNumberStrategy();
} //end while
} //end startGame()
} //end class GamePlay

import java.util.*;
public class Question
{
int rabbitNumber = 10;
int answer;
Scanner scanthis = new Scanner(System.in);

public void question1() {
System.out.println("There are " + rabbitNumber +"rabbits.");
System.out.println("How many will you take (1 or 2) ?");
answer = scanthis.nextInt();
rabbitNumber=rabbitNumber-answer;
System.out.println("Answer was" + answer);
System.out.println("New rabbitNumber is" + rabbitNumber);
System.out.println("AI takes over!");
}
}

public class DeathNumberStrategy {

public void deathNumberStrategy() {
deathNumber = (rabbitNumber/3) * 3;
Question.rabbitNumber;
// 14/3 gives 4. so x/y and then answer*y
// 16/3 gives 5 so x/y and then answer*y
if (rabbitNumber == deathNumber + 1)
{
rabbitNumber = rabbitNumber - 1;
numberTaken = 1;
}
else if (rabbitNumber == deathNumber + 2) {
rabbitNumber = rabbitNumber - 2;
numberTaken =2;
}
else //this is for when the user is winning, and it doesn't matter what ai does.
// // numberTaken ==1or2 (randomize)
{}
System.out.println("Rabbit Number is " + rabbitNumber);
System.out.println("Death Number is " + deathNumber);

} //end method deathNumberStrategy
} // end class DeathNumberStrategy


Please do let me know if there was a better or more efficient way to communicate my code or my problem.
thanks,
dan
colton peterson
Ranch Hand

Joined: Nov 18, 2007
Posts: 97

I would say that getters and setters are your best bet. If you only are going to have one instance of that number per game, then you could make it static, if that helps at all.


www.mormon.org
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38881
    
  23
Welcome to JavaRanch

Please note we have a CODE button; it makes your code much easier to read if you use it.
daniel okeefe
Greenhorn

Joined: Nov 13, 2009
Posts: 4
@colton--thank you. I will certainly use setters/getters if I can't figure out a better design plan,
however, I am loathe to begin setting and getting at the very beginning of my OO learning, as
I have been reading that is somewhat anti-encapsulation. I would love to know how to attempt to
be very OO about it.

Also, I'm going to repost my question using the code tags. Didn't realize it was that easy (Thanks CR)

colton peterson
Ranch Hand

Joined: Nov 18, 2007
Posts: 97

Interesting, I've always been taught that encapsulation was very OO. I don't know for sure, and could easily be wrong however. But beyond that I am lost, as I don't know any other way to achieve what you want to do, except through encapsulation. If there is another way, I would love to learn it.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38881
    
  23
What people say is that set methods allow you to alter the values of fields without going through other methods. Get methods are by no means as difficult; they allow you to find the values and not change them (but mutable reference types should probably be returned as defensive copies). A set method can do some sort of validation of the values passed. There is by no means general agreement on this point; I personally prefer to stick to get methods.

It was a long time after encapsulation and data hiding were described before they were accepted as scientifically valid, but if you read something which tells you encapsulation isn't "OO" you are probably reading the wrong thing.
daniel okeefe
Greenhorn

Joined: Nov 13, 2009
Posts: 4
I think I was unclear.
I have read that encapsulation is very OO, but that set/gets break encapsulation, and that set/gets therefore, are not particularly OO. My desire is to stay encapsulated/OO for as long as possible before having to resort to set/gets.

One of the articles I was reading was this: http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html?page=1. I think it's pretty well written, if you can get past the whole 'evil' thing.
Interesting things said re: design on page 2 and 3. Past that, I get a bit confused.

Like I said before, I will probably use getters if I can't figure out how to do what that article suggests, but I am trying to find information on designing in that way.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38881
    
  23
daniel okeefe wrote:. . . but that set/gets break encapsulation, . . .
I think we are both saying the same thing.
colton peterson
Ranch Hand

Joined: Nov 18, 2007
Posts: 97

hmm, interesting article. It makes sense, but he wasn't as clear as he could have been on how to avoid getters ands setters and still make the code work. If you wanted to avoid getters and setters, you could pass the value of rabbitNumber in a constructor, though I'm not sure if that is any more or less OO then getters and setters
Victor Ewert
Greenhorn

Joined: May 28, 2009
Posts: 17
Interesting... I always thought getters and setters helped in encapsulation, since by using of getters and setters you can control when and how fields can be set or retrieved, i.e. validations can be done before a variable is set etc. I have never purposely tried, to not use them and actually use them without much thought. I guess I should look a little more critically at my code going forward.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38881
    
  23
There are instances (eg the Beans pattern) where setters are required. As you say, a "set" method allows you to validate the value entered before setting. But have a look at these two classesThe deposit and turn methods model the behaviour of real accounts and vehicles better than the set methods.

Now you will have to think when you design a class, you will always have to think how useful each method will be, and whether you need it.
Note a getBalance() or getSpeed() method, which here return immutable objects, or primitives, might be much easier to work with than set methods.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

One thing to keep in mind is that no single rule ever applies to all situations (I think there is an exception to this but I don't know it ;). The article you linked to is saying that you want to reduce the data flow - don't have un-necessary get/set methods. His alternative is to move the work which you do on the rabitNumber into a class which holds the rabitNumber. For example, in your Question class you have this method which uses the rabitNumber:


You could instead store the rabitNumber into a class called RabitGameModel or something creative like that. Maybe it looks something like this:


Your question1() method wants to subtract a value from the rabitNumber. So instead of sharing rabitNumber generate a method which does the subtraction:


The next use of rabbitNumber is to display it. Here you can either generate a normal get method, or if you want to further protect the rabbitNumber and serve just the purpose of getting a displayable value, then you could use method that returns a String:


Then we can re-write the question1() method like this:


Perform the same type of work to the access of rabbitNumber in DeathNumberStrategy. I came up with this:


And usage like this:


This seems like a lot for a single variable, which it is. But it means you can change rabbitNumber to your heart's content and really not affect outside methods. If you had other shared data you might move that into the same class and provide methods used for manipulating it as well. For example, I had toyed with moving deathNumber into the 'RabbitGameModel' class because then I could make sure the deathNumber and rabbitNumber move together. In the end I figured the deathNumber belonged to the strategy more than the game model though.

There is also a lot of room for change. You might provide more 'views' of the rabbitNumber. Right now we only have one - getRabbitNumberAsString(). We could use a getRabbitNumberAsInt() method which would perhaps simplify our interface (we could move the 'rounding' to the strategy class since it does not modify the rabbitNumber). As long as we are clear in our documents that the method is a view, and may not represent accurate underlying data (rabbitNumber could be a double, or a long for example) you could be ok (you are free to change the rabbitNumber implementation as long as that view is available).


Steve
daniel okeefe
Greenhorn

Joined: Nov 13, 2009
Posts: 4
Steve,

Thank you very much for your reply, and Campbell Ritchie too. I'm in the process of compiling and checking things, and trying to understand it all. I'll hopefully have a more intelligent reply soon.

Dan
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: simple game - design choice - classes - accessing variables