Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Too many inner classes?

I learned that inner classes are to be used when an object is closely associated with another object. So a LinkedList class might contain an inner Node class, since each Node exists only in its LinkedList.

I'm thinking about making a game, and am considering making a Map object, with a double array of Tiles, where each Tile is an inner class.

But then I thought that really, the Map class should be an inner class inside the Game class.

Thus we have

class Game {
  class Map {
    Tile[][] grid;
    class Tile {
      ...
    }
  ...
  }
  class Unit {
    ...
  }
  class Player {
    ...
  }
  ...
}

However, this seems excessive, since it results in just one, massive file. Is this a problem? Or am I completely misunderstanding the point of inner classes?

What are the factors one should consider when choosing to make your new class inner or outer and, if the choice is inner, when should the inner class be static?

like image 830
Ypnypn Avatar asked Feb 24 '14 22:02

Ypnypn


2 Answers

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.

like image 86
Tim B Avatar answered Oct 29 '22 08:10

Tim B


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.

like image 44
user207421 Avatar answered Oct 29 '22 07:10

user207421