Language comparison
Posted in software -I’ve been playing around with different programming languages lately. Mostly because (a)
that’s my idea of fun, (b)
I want to build skills so I can apply for a wider range of jobs, and (c)
even if I never use them, they teach me things about programming in the languages I do use. This started out just as a comparison of Java and Ruby, to explain why there are all these ex-Java people making a fuss about Ruby. I’ve since added Groovy, and may eventually add Perl or Scala or something.
The example program is really simple: It just reads a comma-separated file and does some calculations with the data. This is a good representative task; I’ve written a lot of scripts that fit that loose description. The point isn’t so much what it does, but how much code is required to do it in each language.
These all live on GitHub, which gives you a nice interface for browsing around the code.
- Java
- Ruby—the final, object-oriented version
- Ruby—the original, scripty version (I’d expect the Perl code to be pretty close to this)
- Groovy
It’s not that they’re so wildly different, but almost every line in Ruby turns into two or three in Java. And Ruby isn’t just more compact, it’s more concise, more readable. For example, here we’ve got a line we’ve just read from a file. It has a name, a date, and an bunch of numbers, like so:
aardvark,2011-03-01,25,77,13,1,6,79,43,23,18,72,20,77,34,22,18,57,55,12,14,62,57,98,86,75
We need to split it up at the commas and save it into variables. Here’s the Ruby code:
client_id, date, *data = line.chomp.split ','
Here’s the Java code:
String[] fields = line.split(",");
String client_id = fields[0];
String date = fields[1];
String[] data = Arrays.copyOfRange(fields, 2, fields.length);
Not only is the Java code longer, it gives you more opportunities to screw up. Should copyOfRange
take fields.length
or fields.length-2
? I had to check the docs, and I wasn’t entirely sure until I ran it.
The Groovy version is, logically, about mid-way between Ruby and Java in length. I may also be missing some Groovy idioms that would make it shorter.
I’m working my way through Seven Languages in Seven Weeks, so I’ll probably be doing more stuff along these lines soon. Let me know if you want to hear about it. Or not.