Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ever reasonable to nest Java inner classes more than one level deep?

Kushal Paudyal asked how deep you can nest inner classes in Java. The consensus is that while the language itself imposes no limit, the underlying OS and file system may.

Have you ever found a case where two or more levels of nested inner classes are helpful?

Update (11/28): If you consider enum classes, a second level of nesting can make sense. During some recent refactoring, I briefly had an outer class (an HTTP client), an inner class (an in-memory cache), and inside the inner class an enum class (for the cache eviction strategies). This seemed okay, but to @Thorbjørn's point, I continued by extracting the cache class and its inner enum up out of the HTTP client class.

like image 372
Jim Ferrans Avatar asked Nov 23 '09 21:11

Jim Ferrans


1 Answers

No. I have not.

The standard example of a class inside a class is the Builder, where you have a subclass to help create a proper instance given a lot of possible configuration methods.

Personally I would consider a more complex case of nested classes an excellent example of code which needs refactoring.

like image 125
Thorbjørn Ravn Andersen Avatar answered Oct 06 '22 23:10

Thorbjørn Ravn Andersen