This post originated from an RSS feed registered with Agile Buzz
by James Robertson.
Original Post: Sorting 1-2-3
Feed Title: Travis Griggs - Blog
Feed URL: http://www.cincomsmalltalk.com/rssBlog/travis-rss.xml
Feed Description: This TAG Line is Extra
I'm doing some work right now that has a lot of those objects that look a lot like, well, database rows. Objects that are kinda high on instance variables and low on interesting behavior. Eventually, you end up sorting these kinds of things. One of the tasks that arises is sorting these things. Sometimes it's simple. Sometimes it gets long. You sort first on last name. But if last name is same, you want to then sort on first name. So on and so forth. And then different clients want them sorted differently or dynamically. It starts to feel like Lotus 1-2-3 sort key setup all over again.
Tired of the sorting rat race, and desirous to capture the concept that could be tested in a unit, I set out to isolate it. Tests first, here's what they looked like:
With tests in hand, we go and implement an object that responds to value:value:. This is the method that a sortBlock of a SortedCollection will use to determine the sort order of it's elements.
KeyedSort>>value: aLessThanCandidate value: otherCandidate
| a b |
keys do:
[:each |
a := aLessThanCandidate perform: each.
b := otherCandidate perform: each.
a = b ifFalse: [^a < b]].
^false
The standard methods to create and set the keys are left to the student. In the end, it's very handy. I have objects that are sorted on as many as 7 of their attributes, and having this object just really simplifies things. Said code--inlined in the past--has been prone to copy-paste-modify errors.
Two things stand out as really cool for Smalltalk here. The first class nature of blocks. IOW, that we can drop a non block object in place where one might be used by simply impelementing the same API. And that it is so easy AND so efficient to to refer dynamically to method signatures. I know that the Java equivalent to specifying method signatures dynamically with a symbol and invoking them is not anywhere near as terse as that in Smalltalk. How does C# compare? Even more interesting, how well do the analogs to perform: actually perform relative to those systems normal method dispatch speed.