Software 29 Aug 2003 05:10 pm

Commentary on Commenting

Brian Marick posits in Exploration Through Example that code is only as readable as the audience is literate. It sounds obvious on the surface, but he brings out some subtleties in the idea, and links to some interesting non-CS books about understanding style’s affect on meaning.

On initial inspection, I completely agree with his idea. I find that as I have been learning new languages like Ruby and Lisp, the syntax is pretty easy, but what takes time to really absorb is how it is used idiomatically. Reading a lot of other code seems to be the best way to get to it, well coupled with writing code.

Ruby blocks are a great example of idiomatic power in a language. Most of the standard stuff can yield to a block. A great one I discovered the other day was changing the sort behavior on an array. In Java I would create a Comparator class that took the items and compared particular properties. The properties would of course have to implement Comparable explicitly. Then I would pass those things into Collections.sort.

class Thing implements Comparable {
private Comparable someOtherFieldToSortOn;
public static void main(String[] args) {
Collection things;
Collections.sort(things, new Comparator() {
public int compareTo(Object a, Object b) {
return a.someOtherFieldToCompareOn.compareTo(b.someOtherFieldToCompareOn);

In ruby, I just pass a block to the sort call.
class Thing
attr_reader: @someOtherThing

things.sort { |a,b| a.someOtherThingToSortOnb.someOtherThingToSortOn }

This code assumes that you have already implemented a comparable in Java or a in Ruby that is the standard sorter.

In Ruby, the block also gets lexical closure which is really nice as well. I am still figuring out all the ways to use that.

Subscribe to the comments through RSS Feed

Leave a Reply