Seven Low-Cost Ways to Improve Legacy Code
Subject:   Re: 5: Removing Anonymous Inner Classes
Date:   2004-05-31 11:43:53
From:   idarwin
You write:

However, the fact that anonymous classes can't be reused at all generally makes using them a bad idea. In addition, anonymous classes make code harder to read and bloat up the class declaration space of your program.

I'm not sure that it is always a good idea to remove inner classes. Most of my uses of anonymous inner classes are one- to three-line listeners (e.g., in a GUI). Having the handler declared in the same place as the GUI controls that use them makes the code overall more readable than having to go hunting off someplace for it. And having each GUI control's action handler in its own class avoids having a single, large, unmaintainble handler with a separate "if" clause for each of the 35 GUI controls you remembered (not to mention the two you forgot about :-) ). That style of coding is why they deprecated the 1.0 handleEvent() method, after all.

But yes, there are times when inner classes make things worse, rather than better. I prefer to avoid blanket statements like "never use ..." or "always use ...", and simply keep this as one technique among many for writing better code.

1 to 1 of 1
1 to 1 of 1