Thursday, May 24, 2007

Avoid the declaration of anonymous inner classes

Java Transgression #1

Action listener constructs associated with JButton, JTable, etc., (objects commonly seen within Swing applications) are frequently seen employing anonymous inner classes. If using Eclipse's VE and adding action listeners, it's hard to avoid as it places them in your application to provide function for the related component.

Refactoring results in the creation of a listener class, instantiating an object based upon that class and then passing it as the argument for the event listener.

Extending the listener class and assigning it to the component results in the elimination of inner classes altogether. The application will even load faster because the JVM doesn't spend time loading those inner classes.

In addition, employing anonymous inner classes kills any hope for object reuse.

No comments: