Share via


Object Calisthenics: Rule 1: Use one level of indentation per method

First of all a method with a lot of different indentation is harder to understand than a method with less indentation. I also think that each level of indentation typically means you're doing another thing. Look at this code:

 
   1:          public void Format()
   2:          {
   3:              for (int row=0; row<rows; row++)
   4:              {
   5:                  for (int column=0; column<columns; column++)
   6:                  {
   7:                      grid[row,column].Format();
   8:                  }
   9:              }
  10:          }

The nested for loop introduces two levels of indentation. One of them can be refactored into a second method so it looks like this:

 
   1:          public void Format()
   2:          {
   3:              for (int row=0; row<rows; row++)
   4:              {
   5:                  FormatRow(row);
   6:              }
   7:          }
   8:   
   9:          private void FormatRow(int row)
  10:          {
  11:              for (int column=0; column<columns; column++)
  12:              {
  13:                  grid[row,column].Format();
  14:              }
  15:          }

Some people might say that it is just another level of indirection and that we have now made the Format method harder to understand since we also have to look in the FormatRow method to understand what is happening. I think that is only true if you use bad method names I'm perfectly fine with assuming that FormatRow actually formats a row without looking at the code for FormatRow. So if extracting code to a separate method will make your code less readable you're probably not giving the method a very good name.

Some people also scream that more methods means bad performance. First; believe in the compilers ability to optimize code for you. Second; only optimize what is proved to be a bottleneck. I think readability is preferred over any theoretical performance issue. Only real performance issues should be addressed.

Last but not least, this rule is not intended to be used in your production code. We're talking object calisthenics, remember? If you want to apply this rule to your real code you probably want to say use as few levels of indentations as possible in each method.