A Sort Optimization Technique: decorate-sort-dedecorate

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Mon Aug 28 04:53:11 EDT 2006


In <1156723602.192984.49610 at m79g2000cwm.googlegroups.com>, Tom Cole wrote:

> In Java, classes can implement the Comparable interface. This interface
> contains only one method, a compareTo(Object o) method, and it is
> defined to return a value < 0 if the Object is considered less than the
> one being passed as an argument, it returns a value > 0 if considered
> greater than, and 0 if they are considered equal.
> 
> The object implementing this interface can use any of the variables
> available to it (AKA address, zip code, longitude, latitude, first
> name, whatever) to return this -1, 0 or 1. This is slightly different
> than what you mention as we don't have to "decorate" the object. These
> are all variables that already exist in the Object, and if fact make it
> what it is. So, of course, there is no need to un-decorate at the end.

Python has such a mechanism too, the special `__cmp__()` method
has basically the same signature.  The problem the decorate, sort,
un-decorate pattern solves is that this object specific compare operations
only use *one* criteria.

Let's say you have a `Person` object with name, surname, date of birth and
so on.  When you have a list of such objects and want to sort them by name
or by date of birth you can't use the `compareTo()` method for both.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list