Thursday, July 26, 2007

Order Is Disorder

Eclipse offers the possibility to auto-sort the members of a class while formatting its code. After seeing the result of member sorting applied to code I have written, I must confess I find this "feature" totally useless at best, deeply asinine at worst because the cons totally outnumber the pros.

If this sounds too harsh, then here is a more polished point of view from this developerWorks article:
Sometimes it's nice to have members sorted alphabetically to better navigate in your code. Again, there may be arguments against it. Imagine you structure your code so that methods that call each other are located close together for code navigation. The sort would reorganize them, and they may not be in the wanted order.

Sorting members alphabetically is very often counter-intuitive. Let's take javax.servlet.Filter as an example. Which implementation do you prefer:

The alphabetic order
void destroy()
void doFilter()
void init()

The execution flow order
void init()
void doFilter()
void destroy()

The latter is of course the more natural one: time can not be factored out when reading and understanding source code. In this matter, the alphabetic ordering acts as a randomization of the time line of the source code.

On top of time-line ordering, programmers naturally organize related members in groups because it is easier to keep a visual context that covers several methods, hence it facilitates their comprehension. Using the previous example, I would opt to sort the members this way:

void init()
void destroy()
void doFilter()

keeping the lifecycle methods (init and destroy) visually grouped and time-line sorted.

Here again, alphabetic sorting damages another important factor for code understanding: the distance between related statements.

My conclusion is that member sorting is far beyond formatting concerns and should not be automatically applied. If some sort of sorting is needed, it is better to sort the hierarchical outline of the class, as explained in the aforementioned article:
The outline view offers a nice feature to sort members in the view, but not in the code. The specific settings and how members are sorted can be found in Preferences > Java > Appearance > Members Sort Order.