Deep indentation

Having many levels of indentation can seriously hamper readability (and thus the understandability) of code. These indentation levels are normally a result of nested conditional statements and try-catch blocks.

How many levels are too many?

Many people feel that 4 levels of indentation is the limit. This is not a hard rule, but serves as a good guideline.

Another guideline is that your source file should never contain a line of code that gets wrapped around or needs side scrolling. Unfortunately this is dependant on your screen resolution and font size. For some people the limit is at 80 characters (the Linux kernel uses this measure) other people feel that this measure is outdated and wastes screen real estate.

The basic idea is that whenever the amount of indentation levels make it difficult to understand the code, it's too many.

How do I fix it?

One way suggested in “Refactoring: Improving the Design of Existing Code” by Martin Fowler is replacing the conditional with Guard Clauses. Ex.
method body
if condition1 is true
if condition2 is true

can be replaced with
method body
if condition1 is false
if condition2 is true

Sometimes it is possible to rework the logic of the method. You may find that some conditionals are excessive or that it can be simplified further.

Many times though, this is an indication that other problems exist in your code. Things like methods that are too big, constant testing for null, using lots of “Type Codes”, implementing different states in one object, etc. In a lot of these cases, addressing the other problems will also fix the problem of multiple indentation levels.

No comments: