Wednesday, April 09, 2014

Don’t Just Grab the Wheel, Ask the Driver to Turn

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.

4 comments:

Anonymous said...

I might try out that analogy as well. I've always had trouble explaining to kids why public variables are a no-no.

Mike Zamansky said...

Just thinking out loud here.

Let's say you break the class into 4 teams. Something done not infrequently in classes

At any point each team has one player. who controls the inputs. It could be giving an answer to a question or it could be handling a computer interface to an actual game, controlling a robot, whatever.

Now of course the team members should be suggesting to the active "lead" player how to proceed but is never allowed to make the final answer (think family feud, or the crowds in the price is right).

This builds a real class situation similar to the car analogy which wile good would be lost on my city kids that don't drive (yes, they understand it, but it's not as real).

Just a thought.

Alfred C Thompson II said...

I love that idea Mike. I remember well being a HS student who didn't drive. Although I did drive before most of my peers - my Dad as a single parent needed another driver in the family with 4 kids. Up here in NH kids drive early.

Mike Zamansky said...

Yeah - us city kids (you excepting) start late - I didn't learn to drive until after I had left wall street and started teaching.