Let me give you an example of using nested classes that can clarify when such an architecture is suitable. Recently, I needed to create an HTML table by pulling selected columns from the data table and "expanding" them so that the rows become columns and vice versa. In my case, there were two main operations: rotating the data and creating some rather complex output (I didn’t just show the data: each row of the column / data table obeyed the operations for extracting the header, generating image tags, setting links, etc., therefore, using SQL Pivot was not quite right).
After the initial attempt to create one class to do all this, I realized that most of the data / methods fell into three different sections: heading processing, string processing, and rotation. Thus, I decided that the best approach would be to encapsulate the logic for the "header" and "string" in separate nested classes. This allowed me to separate the data stored in each row and program the rotation operations very cleanly (calling a separate row object for each column in your data table). Upon completion of the rotation operations, I generated the output by calling the header object, and then each row object, in turn, to generate my output back to the main class.
Separate classes were not suitable because A) the nested classes needed some data from the master class, and B) the processing was very specific and was not useful elsewhere. Simply programming one large class was simply messy due to confusion around terms such as “column” and “row”, which differed depending on whether you were talking about data or HTML output. Also, it was an unusual job in that I created HTML in my business class, so I wanted to share pure business logic with a generation of user interface. In the end, nested classes provided the perfect balance, and then encapsulated and exchanged data.
Mark Brittingham Mar 26 '09 at 13:24 2009-03-26 13:24
source share