I have been googling around looking for a advantages that one might gain in nesting classes. There are plenty of examples as to how to do this but none that I can find as to the reasons for declaring a class within another. I even consulted my newly arrived “Code Complete” but there was no mention there either. I can see the disadvantage of it being harder to read.
Usually, a nested class is only there to support the functionality of its container class, and has no viability on its own. For instance, it may serve to collect a larger number of parameters for initialization keeping the constructor of the main class manageable; or it may inherit to define a specialized collection that supports the main class.
Semantically, there's no difference to a separate class, but nesting sends a clear message that the class is not to be used on its own.
Use them, if the parent class need some models to work but not all the other classes. So an internal representation/helper for some data.
I've usually used them declared as private, so they could be used for some funcionality needed only inside the outer class, keeping the namespace clean of not needed auxiliary classes.
From my point of view, nesting classes is not mandatory. I usually nest a class only if it's just a small object, only related to a particular class.
there are several design decision that ends with making a nested class:
- you want to make more explicit the relation between two class; a . name is more explicit that two classes in the same namespace
- context-dependent classes as top-level nested classes enclosed by the context-serving class makes this dependency clearer "these things goes togheter"
- avoids namespace pollution
- reduces the number of source files
so there are two principles behind nested classes: dependency and better organization
You might use a nested class to model a concept involved in the implementation of the outer class, but so intimately tied to the outer class that it wouldn't make sense for the nested class to be used in any other context. Nested classes have visibility of and may explicitly depend upon details of the outer class that aren't part of its public API.
A common pattern is for a nested class to implement a public interface, and for the outer class to expose an instance of the nested class via a method whose return type is the public interface. The iterator pattern is one example of this.