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 https://softwareengineering.stackexchange.com/questions/52685/if-you-need-more-than-3-levels-of-indentation-youre-screwed:

for(int i=0; i<10; ++i){
  Object val = repeat(i, someVar);
  if(val.value > 3){
      case DOG:
          doMoreThings(val, mMoreThingDoer);
          // 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"?

  • 3
    There are many ways to reduce the number of levels of indentation. Early return is one of them. Apr 23, 2013 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, 2013 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".
    – user40980
    Apr 23, 2013 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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