Too many inner classes?

The question I would ask is 'Does the inner class make sense as a concept unto itself?' Does an object of type Map have meaning, or does Game.Map add significant value?

I would Map makes sense on its own, and should therefore be an outer class. You can then specify the close relationship of Game and Map using namespaces.


It's not a question of 'too many', at least not until you hit some hard limit. It's a question of what can reasonably be said to belong inside what. A Map will always have Entries, which can be an inner class. A Game won't always have have a Map, so the Map shouldn't be inner to Game.


When to use inner classes is as much art as it is science. Basically look at how big your code file is getting and how big each class is. If a class is big and complicated it should probably go in its own file. If it's small (for example a single function implementation of a listener interface) and unlikely to be re-used elsewhere then it should probably be an inner class.

In fact re-use is probably one of the most important criteria. Anything that can be re-used should be re-used and should be scoped appropriately to enable that.

An important advantage of inner classes is that they can help with encapsulation, keeping the internal implementation of your class internal. If other classes do not need to know about your inner classes (or in some cases even that they exist) then that is an excellent reason for them to be inner.