Skip to main content

The Good, The Bad, and The Ugly

Posted by evanx on October 10, 2006 at 7:55 AM PDT

In Concise Instance Creation Expressions: Closures without Complexity
by Bob Lee, Doug Lea, and Josh Bloch, they propose the following syntax
for closures, as a shorthand notation for anonymous classes with a single abstract method type,
eg. Runnable, Comparator and the like.

   List<String> stringList = ... ;
   Collections.<b>sort</b>(stringList,
      Comparator&lt;String&gt;(String s1, String s2) {
         <font color=#000099><b>return</b></font> s1.<b>length</b>() - s2.<b>length</b>();
      }
   );

At first i thought why not include the method name as follows, for clarity.

   Collections.<b>sort</b>(stringList, 
      Comparator&lt;String&gt;.<b>compareTo</b>(String s1, String s2) {
         <font color=#000099><b>return</b></font> s1.<b>length</b>() - s2.<b>length</b>();
      }
   );

Then i remembered, i just prefer the old familiar anonymous classes, and i'm not much
interested in shorthand.

Take abbreviations for instance. Abbreviation is the Clarity-Killer, which passes through
you and all that remains is Confusion.
Programmers, that don't use IDEs, are not lazy enough!
And inconsiderate. They leave a trail of broken windows like abbreviations and
inconsistent names, and code in need of refactoring, which they can't fix - because
they don't use IDEs! That's why not using IDEs is the root of all evil ;)

Anyway enough of that nonsense. Let's consider Swing event handlers.

   okButton.<b>addActionListener</b>(<font color=#000099><b>new</b></font> ActionListener() {
       <font color=#000099><b>public</b></font> <font color=#000099><b>void</b></font> <b>actionPerformed</b>(ActionEvent e) {
          <b>okActionPerformed</b>();
       }
   });

The following shorthand would avoid the method declaration.

   okButton.<b>addActionListener</b>(<font color=#000099><b>new</b></font> ActionListener().<b>actionPerformed</b>(ActionEvent e) { 
      <b>okActionPerformed</b>();
   });

And the following is as shorthandish as one could possibly make it, as in the above-mentioned
proposal.

   okButton.<b>addActionListener</b>(ActionListener(ActionEvent e) { 
      <b>okActionPerformed</b>();
   });

Considering that in Matisse, Netbeans generates and hides this code, and in general IDEs
generate anonymous class methods for you, to save those keystrokes, is there really a need
for such a shorthand notation? It goes towards having multiple
ways to do the same thing (The Bad), and towards less keystrokes for IDEA-less Clarity Killers
(The Ugly), and anyway what's wrong with anonymous classes (The Good, The Verbose and The Clear)?