Are for loops allowed in the “Clean Code” set of rules

clean codecoding-standardscoding-style

Given the set of rules explained in "Clean Code", can one really use for loops? My confusion stems form the fact that a for loop is a low-level construct per se, thus it can only be used at the very lowest level of abstraction, by the book. But then, does it mean that using the loop is forbidden in those pieces of code that belong to a higher level of abstraction, i.e., the pieces of code where functions are being called?

I'm asking because I tried to look at my code from the point of the view of "don't mix low and high level" as per the book and realised I couldn't even write a for loop. That slowed me down to a crawl (slower than my usual turtle slow coding).

Best Answer

I think you refer to the principle "One level of abstraction per function" in Clean Code.

This general principle makes perfect sense: a level of abstraction is the hiding of lower levels of details, in order to master the complexity. Mixing different levels of abstraction therefore implies that your attempt to hide/encapsulate complexity of higher level is broken by the simultaneous use of lower level, which requires a clear understanding of how both levels are interrelated. So you loose benefits of encapsulation.

This has nothing to do with the value judgment that you give to different instructions. If you consider for to be low level, you could consider the same for if, while, return, function calls, etc...

So you can use the for in your design, without breaking the rule.

Remark: What could break the rule is if you would use a for loop to access a level of detail that should be hidden. For example, if you'd use in a high level function a for to iterate through an array, when you already have a higher level function to perform a search.

Related Topic