Tag Archives: explaining

Explaining closures to a five year old…

Once upon a time, someone on Stack Overflow asked the question, “How to explain Dependency Injection to a 5-year old”

The author of the question was really just looking for a good simple explanation but the title had resonated with people and I was surprised to see that person after person had either declared it impossible or had made a snarky comment about child abuse or something. But the answer was really obvious so I posted my answer: http://stackoverflow.com/questions/1638919/how-to-explain-dependency-injection-to-a-5-year-old/1638961#1638961

And I got more up votes than for anything I’ve ever answered before or since. So when I was asked in a recent job interview if I could explain dependency injection, I laughed, and then I explained why I laughed and what my answer had been. Then later in the interview I was suddenly thrown a new one, “Can you explain closures? No wait, can you explain closures to a five year old.” I have to admit, I vapor locked. I could not come up with an answer that a five year old could possibly understand. To me closures have three elements you have to talk about if you want to explain them (or at least how they are in JavaScript which is where I have the most exposure to them). They are, a repeatable set of code that can be handed around and called in different circumstances, a set of variables which were bound when the closure was created, and another set of variables which can be passed into the closure so they are different every time it is invoked. So I did explain it at that level and the interviewer was pleased, at least to the extent that I got the job.

But I couldn’t let that drop, so I thought about it and it occurred to me that there was a pretty good analogy in a child’s life to closures. So I wrote it down and sent it to the interviewer the next day, and maybe that’s why I got the job after all. But anyway, I give you closures for a five year old…

You know how you like to play Star Wars*? I know what you mean when you say you’re going to go do that and I can tell you to “go play Star Wars” and you understand me.

You can play it in different places, like over at Jimmy’s sandbox and it will be Star Wars on Tattooine or in your big box that is Jabba the Hutt’s palace, but you can always have your Luke Skywalker, Han Solo, and Darth Vader with you so that part stays the same as when you first played it in your own room.

*Substitute Barbie if you prefer.