The woes of Iterable<T> misuse

This will be another computer related post so there is a word of warning for computer n00bs: stop reading now before you find out that you are reading what appears to be gibberish :) For the past two weeks I have dived into the topic of my Bachelor Thesis. It it about computer vision and I shall say no more until I have something to show. Before those two weeks I was working on an "inherited" code in C++ in all it's template glory. And I hated it. Well, it's all a matter of preferences and I completely understand ... ah, screw it, I DO NOT understand morons who write_function_names_like_this ;) ... joke. So I switched to Java and while I am well aware that I have sacrificed some speed I can say that I don't regret it. Now writing code is pure joy, not to mention portability. OK, regarding that pure joy ... there are still bugs, some really interesting ones in fact and that brings us to the main topic of this post: The misuse of Iterable interface in Java and the woes I had with it. With Java SE 5.0 (not so new anymore) Sun introduced a new way of iterating over an object that contains elements (like Vector or ArrayList). If this class implements the Iterable interface, that actually means that it can produce an Iterator object that is then used to iterate through elements. The whole thing would be nothing exciting if not for a shorter way of writing a "for" statement:

for (Object o : list) [
      ...
   ]

Nothing new for some other languages, but at its time really new thing in Java. Of course I had to wait for a year or two before Ihave actually started using it ... maybe too much. I have an list in my code that I had to iterate through. So I use my newly aquired skillz of Iterable interface and its usage towrite a similar "for" statement than above. But the problem is that I also have to iterate through an array of the same size.Every sane programmer would switch to normal for (int i = 0 ...) statement in this case, but not me! Instead I wrote:

int i = 0;
   for (Object o : list) [
      ...
      i++;
   ]

Stupid, but valid. And everything goes fine until we include a condition with a "continue" statement:

int i = 0;
   for (Object o : list) [
      if (...)
          continue;
      ...
      i++;
   ]

Still valid, but not so OK anymore ... each element is connected to exactly one field of the array I used and if the "continue" statement is executed everything goes ... no need to say where. So the point of this story is: don't use Iterable interface just because it looks pretty in a "for" statement.

Written on May 7, 2007 at 11:33 p.m.
blog comments powered by Disqus