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
…
else
…
method body
if condition1 is false
return
if condition2 is true
…
else
…
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:
Post a Comment