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.
Try reasoning a bit more abstractly: in as much as an instance of your class is modeling a real-world entity (a good thing, when you can do that conveniently), instance variables should be all that you need to represent the state of that thing — not artefacts such as temporary results of computations, which don’t correspond to any real-world “state”.
So, for example, consider your class:
and critique it based on the test “is this instance variable actually part of the state, or not?”.
By this criterion,
locationandtotalGasseem fine — a real-world car does indeed have a location, and some amount of gas in it, as part of its real-world state. The others are more dubious.destinationwould be fine if you were representing the car at various spots during a trip, or a leg of the trip — at any given time there would be a present spot, and a destination towards which the car is traveling. But judging from your code that’s not what you’re doing: thedestinationinstantly becomes thelocationif gas is sufficient, so you’re using a simplified model of reality where the car is only represented as being in specific places rather than in route between them (which btw is perfectly fine: any abstraction is, inevitably and usefully, a simplification of reality, and if for your application’s purposes you can abstract away the “traveling between places” state, by all means go for it). The same applies even more strongly to the variables about required and enough gas — not natural parts of the object’s state.So make those local variables, arguments, and return values, for the appropriate methods, i.e., change the traveling method to:
So, some of the values needed for computation (precisely those that are part of the object’s state) are in instance variables, other (the intermediate results of computations that are not actually part of object state) are local variables, arguments, return values.
This mixed approach is sounder and more promising than either your original one (with all those “getter” method calls, eep!-) or the one at the other extreme (where everything and its cousin was an instance variable, for mere computational convenience and quite apart from good modeling approaches).
Since instance variables and local variables therefore get mixed in most computations, many programming styles require them to have distinguishable names (some languages such as Python and Ruby make that mandatory — the instance variable
locationfor example would be spelled@locationorself.location— but I’m talking about styles for languages that do not force the issue, but still allow you to name that instance variablelocation_with a trailing underscore, orm_locationwith anm_prefix, and the like).