At What Point Is It Taboo to Have Loops Within Loops?

coding-standardscoding-styleindentationloops

Just curious. The most I have ever had was a for loop within a for loop, because after reading this from Linus Torvalds:

Tabs are 8 characters, and thus indentations are also 8 characters.
There are heretic movements that try to make indentations 4 (or even
2!) characters deep, and that is akin to trying to define the value of
PI to be 3.

Rationale: The whole idea behind indentation is to clearly define
where a block of control starts and ends. Especially when you've been
looking at your screen for 20 straight hours, you'll find it a lot
easier to see how the indentation works if you have large
indentations.

Now, some people will claim that having 8-character indentations makes
the code move too far to the right, and makes it hard to read on a
80-character terminal screen. The answer to that is that if you need
more than 3 levels of indentation, you're screwed anyway, and should
fix your program.

https://www.kernel.org/doc/Documentation/CodingStyle

I figured it was an unacceptable practice for me to go to a third layer of looping, and would restructure my code (Primarily Qt).

Was Linus joking?

Does it depend on the language or application?

Are there some things which absolutely need three or more levels of looping?

Best Answer

The kernel strongly prefers simple algorithms

While a variety of algorithms may require deeply nested loops within loops, in context of the Linux kernel (in which the quote was said) you generally need quick real time responses. In that context, deep nesting is a smell that may indicate that the code flow is too complex for this domain and may needs to be changed because of it's execution characteristics, not readability or indentation issues.

Furthermore, Linux kernel is different from most application code as for the requirements of auditability and testing - and thus would prefer to not have a 4+ level nested algorithm in a single function. It should be obvious to see what each code fragment does exactly and in detail, including all the possible control flow and edge cases. Deeply nested code hampers that.

Related Topic