I was sitting with some friends the other week and a question came up. Someone asked, “so, when did you last write a for-loop?” We all chimed in, one after another, and the answers varied. Some of us had written fors earlier in the day; others, the previous week. Some of my friends hadn’t written a for in months. And, no, it wasn’t because they’d left programming, it was because they were working in languages where you either don’t have fors or you don’t have to use them often… languages like Ruby, Smalltalk, OCaml, and Haskell.

Well, more power to them. I work in C, C++, and Java periodically. For-loops will always be a part of C. In C++, we you can avoid fors with algorithms and functors (although the syntax is a bit wild), but in Java, you’re still stuck with them unless you opt for the Apache collections library or some homegrown solution. Yes, there’s talk about adding closures to Java, but it’s not there yet.

There’s something very annoying about writing a for. For one thing, you have to deal with a lot of detail that is really “off the side” of what you want to do. If you want to iterate an array in C, you can do this:


for(int n = 0; n < size; ++n) 
    sum += elements [n];

Isn’t it ridiculous that most of the complexity is in the first line, rather than the second? It’s all bookkeeping.

Isn’t it even more ridiculous that we’ve been doing this for years? And, sadly, it’s not because we haven’t tried to abstract our way out of it. Since the beginning of “structured programming” people have looked into ways to make iteration less onerous. I remember Pascal and Ada with their “upto”s and “downtos”.. and there was the CLU language, which introduced the concept of an iterator, which was great, but then we had to live with this for years in Java:


for (Iterator it = orders.iterator(); it.hasNext(); )  {
   Order order = (Order)it.next();
   …
}

It was just insane. And, yes, the for syntax introduced in Java 5 is nicer, but, really, just give me a block:


 orders.each { | order | ... }

So we're moving forward. People are moving towards blocks and closures, but why did it take so long?

Part of it, I think is a historical fear of inefficiency. For the longest while, the idea of using a block in the context of iteration was scary for many people. There's more indirection. And, regardless of whether it was slower, it looked slower. Another part, I think, was a fear among language designers that the vast majority of programmers wouldn't be able to handle blocks or that they would be put off by them. And I think that today we can say that that is obviously wrong. It's just a shame that it took so long to figure out.

So, if I run into those same friends in five years and we have the same conversation, I wonder what the answers will be? Will any of us still be writing fors? Only the C folks.. that's my bet.