Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

What steps and measures can I take to prevent deep indentations in my code?

share|improve this question
2  
A lot of people will talk about refactoring here. Maybe this is too much to ask, but if you posted some (not too long) code that is deeply indented, and people could show you how they'd refactor it. Of course, that probably makes the question language specific then... –  Paddyslacker Sep 9 '10 at 21:34
2  
Use a smaller tab width. –  mipadi Sep 21 '10 at 17:47
5  
Arrowhead anti-pattern. Google it, loads of tips –  NimChimpsky Sep 22 '10 at 10:43
2  
Stop using python :D –  back2dos Oct 8 '10 at 14:18
    
It's time to look at your control and loop logic. Likely your code is more complicated than it needs to be, and a re-conceptualization of the problem will lead to much shorter code. Study good code and learn the techniques. –  Macneil Aug 15 '11 at 2:56

9 Answers 9

up vote 11 down vote accepted

Deep indentation is usually not a problem if every function/method in your program does one and only one thing. Occasionally, it might be necessary to nest conditionals a few levels deep, but I can honestly say I've only written deeply indented code a handful of times in 12+ years of coding.

share|improve this answer

The best thing you can do is extract methods:

int Step1(int state)
{
    if (state == 100)
    {
        return Step2(state);
    }
    else
    {
        return Step3(state);
    }
}

int Step2(int state)
{
    if (state != 100)
    {
        throw new InvalidStateException(2, state);
    }

    // ....
}
share|improve this answer
2  
This also works for complex if-conditions. Taken to the extreme, you'll end up with executable pseudocode. –  pluma Sep 21 '10 at 16:17

Maybe you could consider guard clauses?

instead of

public void DoSomething(int value){
    if (someCondition){
           if(someOtherCondition){
                if(yetAnotherCondition){
                       //Finally execute some code
                }
           }
    }
} 

Do

public void DoSomething(int value){
    if(!(someCondition && someOtherCondition && yetAnotherCondition)){
        return;
        //Maybe throw exception if all preconditions must be true
    }
    //All preconditions are safe execute code
}

If you ever get a chance I'd reccommend you read Code Complete by Steve McConnell. He's got a lot of great advise on these topics.

http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670/ref=pd_sim_b_6

share|improve this answer

Invert your ifs.

Instead of:

if (foo != null)
{
    something;
    something;
    if (x)
    {        
       something;
    }
    something;
}
else
{
    boohoo;
}

I'd write:

if (foo == null)
{
    boohoo;
    return;
}
something;
something;
if (x)
{        
   something;
}
something;

The same applies to if-else blocks. If else is shorter / less nested, then revert them.

Check parameters' values in one place

Check all the parameters for illegal values as soon as you enter your method, then proceed knowing that you're safe. It makes for more readable code, but it also saves you piling up conditional blocks later on and spreading these checks all over the subroutine.

share|improve this answer

Typically, I have seen that deeply indented code is usually problematic code. If you are facing this problem, then step back and evaluate if your function is doing too many things.

At the same time, to answer your question, if there is a need for indentation that deep, I would suggest that you let it be there. For the simple reason that in such code, the indentation will help since it is likely to be a very long piece of code.

share|improve this answer

Break nested components (especially repeated ones) out into separate functions (this is easier if your language supports closures) or replace a series of nested loops with a recursion.

Also, indent two spaces instead of four.

share|improve this answer
5  
Once you've gone to the step of changing your tab width, you're in deep trouble... –  Daenyth Sep 21 '10 at 20:33
    
Two-space tabs are the hard stuff.... –  David Thornley Sep 22 '10 at 20:03
6  
Changing the indent is just a way of hiding the problem not a solution –  Murph Oct 8 '10 at 14:51

I don't see deep indentations as a categorical problem to be removed (nor do I see refactoring as the true answer for everything).

Typically instead of nested ifs, I like to write logical statements:

if (foo && bar && baz) 

rather than

if foo 
 if bar
   if baz
share|improve this answer
    
The problem is, there do also exist for and while loops that don't fall under this rule. –  Tom Wijsman Sep 22 '10 at 18:00
    
@TomWij: I am not trying to induce a categorical imperative about style. –  Paul Nathan Sep 22 '10 at 18:07
    
??? ` ` ` ` ` ` –  Tom Wijsman Sep 22 '10 at 18:31

I didn't believe it myself, but according to Code Complete this is an appropriate place to use break (if your team is on board). I'd imagine this is more acceptable with C++ programmers though, where break used in switch statements than it is with Delphi programmers where break is only used when you don't feel like writing a while loop.

share|improve this answer

Indentation is really a think to fight, indeed. What I learned to do is to divide the method into pieces first, then use a weird trick to skip every following pieces if one piece failed. Here is an example :

Instead of :

 {if (networkCardIsOn() == true)
     {if (PingToServer() == true)
        {if (AccesLogin(login,pass) == true)
             {if (nextCondition == true)
                ...
         }
     }
 }

I currently write :

 {vbContinue = true;

 if (vbContinue) {
       vbContinue = networkCardIsOn();
       if (vbContinue == false) {
             code to Handle This Error();
       } 
 }

 if (vbContinue) {
       vbContinue = PingToServer();
       if (vbContinue == false) {
             code to HandleThisError2();
       } 
 }

 if (vbContinue) {
       vbContinue = AccesLogin(login,pass);
      if (vbContinue == false) {
             HandleThisErrorToo();
       } 
 }
 ...

This has seem strange to me at a first, but since I use this, the maintenance cost has been divided by half, and my brain is cooler at the end of the day.

In fact, the gain introduced by this "technique" is that the code complexity is really divided because the code is less dense.

While reading the code, you don't have to remember anything about the past conditions : if your are at that point X in the code, the previous steps are passed and have succeeded.

Another gain is that "escape path and condition" from all those nested "if-else" is simplified.

share|improve this answer
    
Can you elaborate on "the maintenance cost has been divided by half" Also, how would you really know which if halted execution ? –  Chris Sep 22 '10 at 10:19
    
I've done some editing. I hope I answer your questions... –  Pierre Sep 22 '10 at 10:40
2  
If you want to go even simply, you have a goto error_handling line. –  Paul Nathan Sep 22 '10 at 17:26
    
That's not nice. Sorry, but its just not. Then again I'm weird –  Murph Oct 8 '10 at 14:53
3  
instead of emulating a try catch why not use one directly ? –  Newtopian Aug 15 '11 at 5:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.