Women in Technology

Hear us Roar

  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.

Full Threads Newest First

Showing messages 1 through 1 of 1.

  • Re: 5: Removing Anonymous Inner Classes
    2004-06-04 04:57:59  Robert Simmons, Jr. | O'Reilly Author [View]

    I would disagree with declaring a class that can be used only once on general OO design principles. You may dislike the IF structure but actually you are incurring massive overhead in the class declaration in order to avoid the if structure. In addition, the special access rules for anonymous classes makes them often difficult to manage and debug.

    Furthermore, of you have 35 ifs in your actionPerformed method, you might really want to think about the usability of your GUI and see whether it cant be improved. If It cant, then there are other options using reflection that are quite fast for dispatching.

    Naturally this is my opinion. However, it is an opinion that has solidified over years of consulting work and unrelenting issues with anonymous listeners.