Wednesday, September 17, 2008

Prevent unnecessary indentation

Code that is heavily indented is difficult to read (especially if the method does not fit on a single screen anymore).

Instead of this code …

   1: void Test(string input)
   2: {
   3:   if (input != null)
   4:   {
   5:     if (input.Length > 0)
   6:     {
   7:
   8:     }
   9:   }
  10: }

… write this code:

   1: void Test(string input)
   2: {
   3:   if (input == null) return;
   4:   if (input.Length == 0) return;
   5:  
   6:
   7: }

4 comments:

Anonymous said...

I totally agree!

Anonymous said...

this better: if(string.IsNullOrEmpty(input) return;

Unknown said...

On the other hand... methods with multiple exit points are also hard to read.

Not that I'm disagreeing with you, I'm just ambivalent on the matter.

mike said...

I think this is largely a matter of personal style. In your example here, I agree. However there are times when regular old curly-braced, indented blocks are preferred. Consistency is more important to me.