We’re learning about classes and related topics like data hiding and using methods rather than public data in my programming class these days. One of the students asked why we couldn’t just access public data from calling programs. One hears that all the time.
I asked him if when he was a passenger in a car he would ask the driver to turn or would he grab the wheel and turn it himself. I’m not sure is sunk in right away. The analogy didn’t seem to hit him as smoothly as it did me. The more I think about it the more I like it though.
We want the methods in a class to take care of the actions. We, the programmer using objects of that type, really don’t want to be making assumptions about how everything works internal to the class. There may be factors we don’t know about. Just like as a passenger in a car we may not be aware of things the driver is aware of.
The driver knows how responsive the car is, what sort of traffic there may be around the car, and a bunch of other things that we as a passenger may not be aware of. We’re much better off asking the driver to turn and letting them do it their way than taking things into our own hands.
This may be an analogy I can develop and use. Maybe it will help me to convince my students of the wisdom of data hiding and passing messages and requests.