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.

I made the case to coworkers that deep levels of control flow was harmful to the readability of code.

Example, taken from the relevant stack overflow question If you need more than 3 levels of indentation, you're screwed?:

for(int i=0; i<10; ++i){
  Object val = repeat(i, someVar);
  if(val.value > 3){
    switch(val.item){
      case DOG:
        if(mProcess){
          outputToUser(val);
          doMoreThings(val, mMoreThingDoer);
          if(mRepurpose){
            addExample(val);
          }
          // and so on, and so on...

As with most things, it's trivially easy to find opinions on this topic.

I'm wondering however if someone can contribute more to it than that.

Has there for example been done an actual study relevant to the problem?

Or can other arguments be made that go beyond "I like X better"?

share|improve this question
2  
There are many ways to reduce the number of levels of indentation. Early return is one of them. –  Robert Harvey Apr 23 '13 at 17:44
    
If "proof by authority" is acceptable, you might use the relevant material from Microsoft's Code Complete (2nd ed.), which IIRC recommends no more than 3 or 4 nesting levels in Sec. 19.4 (arguing clarity of understanding is lost beyond that point). –  hardmath Apr 23 '13 at 17:45
1  
Every level of scope adds additional things that you need to keep in your head to properly understand the functionality of the code. The working memory of a human isn't that big. Consider also, the complexity of unit testing the code which does "more than one thing". –  MichaelT Apr 23 '13 at 18:11

1 Answer 1

Quick googling shows that some research has been done. For instance, this paper shows that there's a value of cyclomatic complexity of code that minimizes bug rate:

a shallow sigmoid graph

Probably deep nesting may be fine as long as it does not branch at every point. That is, a having many nested conditions on top, as in your example, is probably fine, since it's essentially one condition, just not written as a conjunction.

OTOH if your switch statement below is large and has seriously non-trivial branches, the 'you're screwed' clause may apply.

share|improve this answer

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.