Inner class for stepdown rule
Inner and nested classes (static or not) are not only for passing as anonymous classes for other component or not to expose special derivatives to the public. It is also useful to organize your code layout to improve readability.
I present two usage of class to improve readability:
- group methods together to see clearly which functions are belonging to each other and which is belonging to an other method.
- simplifying parameter passing hell for service methods (common in Spring - e.g.)
Group methods together
The summary of this concept is to organize code the following way:
- Main function
- f1 used in main
- f2 used in main
- f21 used in f2
- f3 used in main
- f31 used in f3
- f32 used in f3
- f33 used in f3
- f331 used in f33
Applying all other rules in Clean Code it is a meaningful advice. For example when considering the rule of a function is doing one thing and a function has one abstraction level only we must have sever (private) method in the class. It is clear that the file can be difficult to review. Such a layout makes easy to identify which lower level function is belonging to which higher level function. So you could skip them if you are not interested in the lower level stuffs.
But modern IDE-s are not supporting this kind of formatting. When let IDE formatting the code all unction will be indented to the same level. Except….
Except we are introducing some kind of extra block which will be indented. And here we can use a nested class.
After (introducing only one layer of grouping):
Simplifying parameter passing
In service centric code base (like the one easy to make when using Spring , or simply a legacy code to take care ) you might start calling a service method with a small number input parameter which is increasing as we are going deeper and deeper in the call stack.
And here it is an other case of using inner classes. Their only purpose is to make parameters class variable and simplify method calls.