I keep having problems deciding how I should create my classes internally. Initially I would have an external class handle all the variable management:
String destination = car.setDestination("San Fransisco");
int totalGas = car.getAmountOfGas();
int requiredGas = car.gasRequiredForDestination(destination);
boolean enough = car.hasEnoughGas(totalGas, destination);
if (enough)
car.travelToDestination()
But it seemed really strange to me that another class should be doing all the work for the car class's data, since the car should be able to do most of the work itself. So to fix that I thought... "hmmm let me just stick all this in the class where it seems like it should go". I figured by doing this I could avoid having to pass so much data back and forth between methods. So then I got this:
Class Car {
String location = "home";
String destination;
int totalGas = 0;
int requiredGas = 0;
boolean enoughGas = false;
public Car (String destination, int totalGas) {
this.destination = destination;
this.totalGas = totalGas;
}
public boolean travelToDestination() {
getGasRequiredForDestination();
hasEnoughGas();
if (enoughGas == true)
location = destination;
}
So the problem I encountered here is that now yes I don't have to pass the data around and things look real clean, but now I am dependent upon each function to return the value to the instance variable. Which in itself isn't terrible, but this just seems very wrong to me. At the same time I think to myself "well I doesn't make sense to pass all this data from one place to another when it seems like I should just manipulate the instance variables. On the other hand my programs end up having 6 lines in a row of:
myMethod {
doThis()
doThat()
checkThis()
checkTheOtherThing()
}
I never really see things done this way in real life so I'm trying to figure basically A) if this is wrong B) if so when should we stick information in instance variables rather than pass it all around. Object Orientation allows us to do this but I don't know if it's a good thing. C) Are there any OO principles involved in doing or not doing things this way? Maybe something I'm violating that I'm not aware of?
I've been programming OO for a long time but I tend to have issues like this on and off so I was hoping to sort it out. If there are any book recommendations that deal with the trickier side of OO I'd be interested in that too.
EDIT: I should have said right off that this is a made up example so there are things in the real world I probably would not do this way necessarily. But I needed some sort of example as the code I had was too complicated.