Friday, December 03, 2004

Non static inner classes

It’s funny how you can know about a language feature for a long while before you really get it. That’s the way I feel about non static inner classes. I’ve generally avoided them until now for a couple of reasons.

First, you often see non static inner classes used in Swing code samples in their anonymous form like:

setButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something…

I’m not a fan of this style of coding for more than the most trivial declarations. I just don’t like how the code reads.

Second, there’s some overhead associated with non static inner classes that can be avoided if you make them static so I’ve also avoided them on principle.

So this begs the questions, why the change of heart.

I was working on some old code I wrote yesterday that was really irking me. The main class in question had a bunch of public methods. Some of the public methods formed the true API of the class, while others were only public because they implemented an interface the class used to plug itself into another class to listen to events. In this case some of the methods had similar names so it was hard to tell which one the user of the class should call without reading the doc.

As I pondered this mess it dawned on me that this is exactly the sort of problem a non static inner class would be a great solution for. By simply making a non static inner class that implements the adapting interface I would be able to move the interface methods out of the API and I wouldn’t need to implement any delegation code to pass state between different objects. Doh!

This may be painfully obvious to you all, but it was a mini epiphany for me.

Post a Comment
The Out Campaign: Scarlet Letter of Atheism