Hacker News new | ask | show | jobs
by Manfred 941 days ago
One of my students in a summer school class about programming just couldn't get their head around what a variable was. These concepts are very hard to teach when you are very familiar with them and they come natural to you.
3 comments

A variable is a box where you can store a certain type of an object. For example, you can have a box with the right size and shape to store toy cars. At one point the variable (box) may contain a red toy car, and at another point it may contain a blue toy car.

If you try to put a banana in there it won't fit because it has the wrong shape for that. We say that the type of the variable (the box) doesn't match the object.

The analogy can be extended to talk about null values (empty boxes), arrays (boxes with slots for multiple objects), etc.

The concept of a variable is just the tip of the iceberg: the syntax for dealing with variables (e.g. assignment vs. testing equality) is difficult for newbies to grasp.

Next level of difficulty for newbies is arrays: understanding expressions to set and get values in an array; variables that hold indexes; non-numeric indexes; each of these is a potential huge stumbling block for newbies. And remember, these are just basic programming skills. Things get much harder from there.

The concepts of data manipulation, let alone the mechanics, are difficult for many newbies. Some never get past that point.

That analogy is heavily stretched with dynamically typed languages, you could say that it's a box that can hold anything, but then the value of the analogy falls apart.
As you point out, all it takes to describe dynamically typed languages is describing a variable as a box that can contain an object. It can contain a fish now and a truck later. What is the problem? Assignments, l-values and such work just fine as far as I can tell.

The analogy works because it's not far removed from what is actually happening in memory. And while laypeople don't know what computer memory is, they have a good intuition about boxes.

Did they not learn about variables in math class?

That's where I learned before I ever saw any code. When I did see the code I was confused by "x = x + 1" since it makes no sense mathematically, but assignment and state were obvious and intuitive after that.

teach them about memory first