Anonymous vs named inner classes? - best practices?

Solution 1:

One advantage of anonymous inner classes is that no one can ever use it anywhere else, whereas a named inner class can be used (if only by the class that created it if made private). It's a small distinction, but it does mean that you can protect an inner class from being accidentally used elsewhere.

Also, using the anonymous inner class gives anyone reading your code a head's up - "this class is being used just here and nowhere else." If you see a named inner class, someone might think it'd be used in multiple places in the class.

They are very similar, so neither point is a game-changer. I just think it helps for clarity if you use anonymous inner classes for one-offs, and named inner classes when it's used multiple times within the class.

Solution 2:

(Counter point to Daniel Lew)

One disadvantage of anonymous inner classes is that no one can ever use it anywhere else, whereas a named inner class can be used (if only by the class that created it if made private). It's a small distinction, but it does mean that you can help ensure that an inner class is not accidentally recreated elsewhere.

Also, using the anonymous inner class gives anyone reading your code a harder time as they then have to parse this class that came out of nowhere. Using a named inner class you are able to organize the source more.

I have seen cases where there are two (or more) anonymous inner classes with the exact same code. In GUIs especially (where you may have multiple controls performing the same action) this can crop up (and I am talking production code, not code that my students have written).

The readability issue goes both ways, some people find anonymous inner classes better as it lets you see what is going on in once place, others find it a distraction. That part comes down to personal preference.

Also making an class static is more efficient, if you are declaring an anonymous inner class in an instance then there will be more overhead, which, if you don't need access to the instance variables, is wasteful (but probably not worth worrying about until it presents as a problem).

My personal preference is to use non-anonymous classes as they allow for more flexibility when the code is modified later.