Archive for the ‘Success stories’ Category

Language-neutral sort block behavior

February 12, 2009

Developers frequently need to sort collections according to specific sort criteria.

A common and powerful idiom is to supply a two-argument block that, when evaluated with two elements from the collection, returns a value indicating the desired (sorted) order of the two elements. This “sortBlock” is applied to each of the elements in the collection (in some order), and the result is returned as the now-sorted collection.

So far, so good. The problem is in the semantics of how the sort block is applied, and in which order the elements of a given collection are passed to the sort block.


Smalltalk and Python use different semantics for the sort block, and apply the block in different sequences for the same initial collection.

In Smalltalk, a sortBlock is called with two elements (I’ll call them “arg1” and “arg2”), and is expected to return “true” if arg1 is to be inserted before arg2 and “false” otherwise. In Python, a sortBlock is called again called with two elements, and is expected to return -1 if arg1 is less than arg2, 0 if they are the same, and “1” if arg1 is greater than arg2.

Leaving aside, for the moment, the debate about which behavior is correct, the point is that they are different. The implication of this is that the developer is forced to think about and code for the specific language (in this case Smalltalk and Python) of a particular fragment of code.


The Zeetix solution is to encapsulate this semantic difference in the SortedCollection class itself, so that the programmer doesn’t have to think about it. The platform can, if desired, support the ability to choose whatever semantics are desired — and that choice is then automatically applied across the board, regardless of the current language binding.

Example Problem
Behavior, the (abstract) superclazz of Metaclazz and Clazz, provides a “subclazzes” method that answers a sorted collection containing the immediate subclazzes of the receiver, ordered according to their “symbol” (the name by which they are referenced in the ecology that contains them).

The Behavior.subclazzes method should answer a SortedCollection with two elements — Clazz and Metaclazz, in that order. Behavior clazz also has two subclazzes, Clazz clazz and Metaclazz clazz, in the same order.

The KernelTest.CoreTest.KernelCoreLoadsTest test case was failing testBehaviorLoads, because the SortedCollection instance returned by Behavior and BehaviorClazz was ordered incorrectly.

My inspection (in the debugger) of the failing test showed that the result was, in fact, an instance of SortedCollection and contained the correct objects. They were, however, in the wrong order. Clearly, SortedCollection was sorting incorrectly.