making hard things easy, the impossible, possible

Archive for the month “October, 2013”

One of the biggest advantages of using Smalltalk is clear expression. Because of the syntax and message passing, a non-programming domain expert would likely understand the intent of well written Smalltalk code that provides a solution in their area of expertise.

Over time Smalltalkers have found ways of integrating methods into the base libraries with the primary intention of using them to create clear, terse code. Often a developer can peruse a Smalltalk class and discover methods to use in talking to their objects. Occasionally, there are clever enhancements that are not obvious without a good example.

Some recent enhancements in enumeration and sorting are good examples of this.

Enumeration

Some enumerators like select: collect: reject: are widely used and fundamental

evenNumbers := (1 to: 100) select:[:ea | ea even].

Can be written slightly shorter as:

evenNumbers := (1 to: 100) select: #even.

squared := (1 to: 100) collect:[:ea | ea squared].

Now can be written as:

squared := (1 to: 100) collect: #squared.

Under the hood

How was this done? You might think at first that the enumeration methods were modified to accommodate this. They were not, which is part of the beauty of this solution. Instances of Symbol can respond to #value: used by enumeration, and they send the message (represented by the symbol) to the receiver.

Sorting

Sorting is something fundamental to many algorithms and applications.

Sorting can often be as simple as:

sortedNumbers := myNumbers asSortedCollection.

When the objects in the collection know how to compare themselves.

For more specific sorts:

employees asSortedCollection:[:a :b | a lastname <= b lastname].

And even subSorts:

employees asSortedCollection:[:a :b |

a lastname = b lastname

ifTrue:[a firstname <= b firstname]

ifFalse:[ a lastname <= b lastname] ].

This can be done in a new, simple and clear manner:

employees sorted: #lastname ascending.

employees sorted: #lastname ascending, firstname ascending.

What if you need a calculation in a block?

emloyees sorted: [:ea | ea …. ] ascending

What I like about this is that this technique is far terser, and the intentions of the simpler code are clear and simple. Any drawbacks? You need to understand this by example, and will not get the big picture simple by browsing the #ascending method in class Symbol.

Bottom line:

Add this to your developer techniques list and your sorting code will be shorter, simpler, clearer, and more easily understood …. and isn’t that what Smalltalk is all about?