Java Iterable Boilerplate Considered Annoying

Here is a concise illustration of what I don’t like about Java.

I have an object that is a list of (MyObject, Integer) pairs that I want to be able to iterate over using a for loop like so:

for (Pair<MyObject, Integer> obj : myPairList)
   // ... do something ...

So I tap a few keys in my IDE and it obligingly creates the template code needed to do this.

   public Iterable<Pair<MyObject, Integer>> objectIntegerPairs() {
      return new Iterable<Pair<MyObject, Integer>>() {
         public Iterator<Pair<MyObject, Integer>> iterator() {
            return new Iterator<Pair<MyObject, Integer>>() {
               public boolean hasNext() {
                  return false;
               }

               public Pair<MyObject, Integer> next() {
                  return null;
               }

               public void remove() {
                  throw new UnsupportedOperationException();
               }
            };
         }
      };
   }

Quick, what does the above code mean? Unless you’re an experienced Java programmer who has grown accustomed to this idiom, this rickety snarl of anonymous classes and generic types is incomprehensible. And I’m not even getting into the difficulty of filling in the template with actual code. In the worst case you will spend days of development time writing something than in Ruby would have literally taken seconds.

I don’t think this is a flaw in Java so much as an impedance mismatch between the way it was originally designed and the way I currently like to think. Except for the runtime type erasure flaw, Java makes object-oriented programming easy. However, it makes no particular effort to make list-based programming easy, and so that naturally ends up hard. This was a perfectly reasonable choice to make in the early- mid-90s, when Java was coming up against the background of C++. Bending over backwards to make for loops look pretty would have seemed like a quirky indulgence. Start down that road an you’ll be wanting list comprehension, yield statements, anonymous functions that aren’t awkwardly bolted on–you might as well rewrite Lisp on the JVM. I can see how this would have seemed like a poor allocation of effort at the time, but two decades later it is precisely the future I wish to go back to.

You can’t be things to all people, but it remains an open question how close you can get.

Advertisements
This entry was posted in Those that have just broken the flower vase. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s