Use Nested Classes to Organize Complex Classes
The ability to nest one class inside provides a powerful way to encapsulate code inside a class to organize complex functionality used within a single class. A nested class looks like this:
Public Class MyClass
…code for the class…
Public Sub SomeMethod()
Dim mnc As MyNestedClass
mnc = New MyNestedClass()
…using the nested class…
As the example shows, in the surrounding host class you can instantiate the nested class and use it. No other class, however, can access the nested class. Nested classes give you a way of organizing the functionality of the host class without exposing that functionality to other classes (or cluttering up your IntelliSense lists with new classes that are only useful in one place -- the host class).
For instance, in a recent application, I needed to manage the permissions and privileges for three levels of users in a form. I created a class for each type of user, with each class holding all (and only) the code for managing what that type of user was allowed to do. Any permissions-related code that was shared by all the users I put in a base class that the three user classes inherited from, giving me four classes altogether. This design cleaned up and organized my permissions code while simplifying the code in the host that set permissions in the form's user interface: the host class just instantiated the right nested class and called its permissions-related members.
Since these classes were only relevant to that single form, I nested all four classes within the controller for that form. With that design, code in the form could instantiate the nested classes and use their members, but the classes didn't appear in any IntelliSense lists outside of the host class.
If you do need to make a nested class available to the outside world, you can add a property to your host class that returns the nested class (as I did in a recent column on creating a fluent interface).
And, of course, you can argue that any class that needs nested classes is too big and too complicated, and is probably violating the Single Responsibility Principle. But that's a different discussion.
Posted by Peter Vogel on 01/09/2014 at 2:32 PM