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

One the Clean Coders videos and also in the Clean Code book there is a specific section about functions and the way to organize the layout of them (look for The Stepdown Rule in section Functions).

The summary of this concept is to organize code the following way:

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.

Before code

1  void main(){
2    f1();
3    f2();
4  }
5  void f1(){...}
6  void f11(){...}
7  void f12(){...}
8  void f2(){...}

After (introducing only one layer of grouping):

 1  void main(){
 2    new F1().f1();
 3    new F2().f2();
 4  }
 6  private class F1{
 7    void f1(){...}
 8    void f11(){...}
 9    void f12(){...}
10  }
11  private class F2{
12    void f2(){...}
13  }

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.


 1  void main(String in){
 2    ...
 3    f1(in, new List());
 4    ...
 5  }
 7  void f1(String in, List collector){
 8    ...
 9    f2(some_other, collector, Option.WHATEVER);
10    ...
11  }
12  ...

And here it is an other case of using inner classes. Their only purpose is to make parameters class variable and simplify method calls.

 1  void main(String in){
 2    ...
 3    new F1(in, new List()).f1();
 4    ...
 5  }
 7  private class F1{
 8    String in;
 9    List collector;
10    Object some_other;
11    Option whatever = Option.WHATEVER
12    // constructor are not included in the sample. 
14    void f1(){
15      ...
16      f2();
17      ...
18    }
20  }
21  ...
Jul 07, 2014
comments powered by Disqus