Monday, October 02, 2006

Sorting things out

Here is a simple problem. One that I am sure many of us would have encountered when programming. You are given a set of objects -- say customer orders -- such that each object is a fairly complex collection of attributes. Customer Order definitely qualifies. Now that you have this collection, I want you to give it to me sorted by order date.

Simple enough, right? All you need to do is sort them. But wait, you don't want to _write_ a sorting algorithm, do you? Really, how many of us have actually written a sorting algorithm since we left school? And rightly so -- others have done it well, have put it in a library for you to use, have tested it, and have written books about how good their library is, so really there's no point in writing one yourself. So, coming back to customer orders, how do you go about sorting them?

If you do it in C++, you'll probably rely on STL or something similar to manage your collection. In order to make your collection sortable, you will have to make sure your objects are 'Comparable' and the comparison works on the order date field. Simple but probably not simple enough. If you are a Java programmer, you probably did something similar.

C actually did it a little better. In the sort function you could pass in a pointer to the comparison function that would be called for comparing two objects in the array being sorted. All you had to do was to write a function that returned the comparison result based on date.

The reason C is even better is that when you need to have several different ways to sort this array of objects, it starts to get onerous with the 'Comparable' approach. You probably would have to wrap each class into specific Comparable versions for each field. In C you would just write a small function for the new field, and use that.

In Ruby, however, if you want to sort an array of objects, all you need to do is write code that looks something like this:

orders.sort! { |a,b| (a.order_date <=> b.order_date) }

This just feels beautiful. Sort it on customer name, no problem. Just sort it with a different code block. One line of code. That's it. There are no complex design patterns to worry about, no layers of Objects. It is definitely similar to C, but far more elegant, and far simpler. I recall it took me a few tries to figure out the function pointer declaration.

This kind of stuff makes it much simpler to design lean API -- because despite being lean, it doesn't require a bunch of glue code to make it work for a particular application.

Minimality of code has many, many virtues. Not the least of which is that less code implies less bugs. And that has to just spell happiness for developers, project managers and consumers alike.

No comments: