Archive for April, 2007

List Manipulation in Java and Ruby

Friday, April 13th, 2007

After doing a bit of Ruby coding, I get that "this should be easier" feeling when working in Java for any length of time. An example of that is doing some simple operation on a list. In this case, I’m wanting to do something trivial.

The task is simple: given an unsorted list of objects, find the lowest value of some property.

In Java this would look something like:

Date startFoo = null;
for(Foo f : getFoos()) {
  if (startFoo == null) {
    startFoo = f.getStartDate();
  } else {
    startFoo = (startFoo.before(f.getStartDate()) ? startFoo : f.getStartDate());
  }
}

And in Ruby, this would look something like:

get_foos.map{|f| f.start_date}.inject{|low,start| low < start ? low : start}

Not a huge difference in code length or complexity, but once you start needing to do this a few times the extra verbosity starts to add up. All that typing makes it harder to build momentum and get into flow while coding. In any example more complicated than this you’d often have to explicitly handle generic declarations or type casting (which means even more typing). In Ruby you can pretty much think of how it’s going to work, and just run with it (once you grok how map and inject work).

There is a lot of talk about adding closures to Java 7. That’s something I’d love as it would make a lot of the techniques used in Ruby possible in Java. I just hope that it’s done better than when generics were introduced in Java 5. (We’ve just upgraded one of our products from 1.4 to 5, and I’ve been exposed to generics in action for the first time. Not so impressed so far… but that’s another post.)

UPDATE

As pointed out by robert in the comments, there is an even simpler approach:

get_foos.map{|f| f.start_date}.min

Cheers :)