Java – Best practice with respect to anonymous classes in UI applications

design-patternsjavaui

When working with user interface based Java programs, one way of attaching behaviour to a certain actions (e.g. to a button click) is through the use of anonymous classes. In the example below, the GUI framework is SWT, however I have the same issues with Swing or Android UI components. Namely the structuring of my programs.

MenuItem sampleMenuItem = new MenuItem(popupMenu, SWT.NONE);
sampleMenuItem.addSelectionListener(new SelectionAdapter() {
    public void widgetSelected(SelectionEvent event) {
         doSomething();

         // handle all table entries
         for (int i=0; i<10; i++) {
             doSomething2();
         }

         doSomething3();
         doSomething4();
    }
});

Of course, some might argue that the amount of code in the sample above already warrants for the creation of a dedicated class that contains the logic. This is also suggested by Sonar's "Anonymous classes should not have too many lines" rule.

Interestingly, this rule also specifies that:

squid : S1188 – While waiting for support of closure in Java, anonymous classes is the most convenient way to inject a behavior without having to create a dedicated class. But those anonymous inner classes should be used only if the behavior can be accomplished in a few lines. With more complex code, a named class is called for.

However, since closures have not yet arrived in Java, my question is whether there are any more elegant solutions than:

  • writing a bunch of code within anonymous classes which has all sorts of drawbacks (limited reuse, slower navigating through the code, …)
  • creating a huge number of dedicated classes which themselves all might have very limited functionality (i.e.: over-engineering, …)

To extend my question: I would also like to know what are the best practices with respect to this aspect of Java based UI applications? Are there any well established patterns?

Best Answer

The only pattern I've seen, that works is "When the code gets to hard to figure out what's going on, it's time to stop using an anonymous class.".

In your example, the method body is the anonymous class. I might move the "new SelectionAdapter" onto it's own line, to make the opening paren a little more obvious, but otherwise it's fine. Where you get into trouble is when a random person can no longer figure out where the anonymous class and method code are.

I've also create a private variable, or method to hold the anonymous class. I put that kind of thing at the bottom of the class, out of the way. It kinda sorta bridges the gap between a whole new class, and keeping it in the middle of the code. Some people consider it bad style though, but my general rule of thumb is to code for readability first.

Related Topic