Java (anonymous or not) inner classes: is it good to use them?

Guillaume picture Guillaume · Feb 17, 2010 · Viewed 18.1k times · Source

In some of my projects and in some books was said to not use inner class (anonymous or not, static or not) - except in some restricted conditions, like EventListeners or Runnables - is a best practice. They even were 'forbiden' in my first industry project.

Is this really a best practice? Why?

(I have to say that I'm using them a lot...)

-- EDIT ---
I can't pick a right answer in all these responses: there's part of rightness on mostly all of them: I'll still use inner classes, but I'll try to use them less often !

Answer

Uri picture Uri · Feb 17, 2010

In my view, 90% of inner classes in Java code are either entities that are associated with a single class and were thus "shoved in" as inner classes, or anonymous inner classes that exist because Java does not support Lambdas.

I personally don't like seeing complex inner classes. They add complexity to the source file, they make it bigger, they're ugly to deal with in terms of debugging and profiling, etc. I like separating my project into many packages, in which case I can make most entities top-level classes that are restricted to the package.

That leaves me with necessary inner classes - such as action listeners, fake "functional" programming, etc. These are often anonymous and while I'm not a fan (would have preferred a Lambda in many cases), I live with them but don't like them.

I haven't done any C# in years, but I'm wondering if the prevalence of inner classes or whatever the C# equivalent is dropped when they introduced Lambdas.