Rule to limit all deep nesting

Deep nesting makes code hard to read and hard to reason about.

Currently Clayton only offers a rule to check for nested if, but there are other things which cause deep nesting such as for, while, try, inner classes.

The rule should not care about “if” only about the depth of the nesting.
Ideally, the rule should only allow blocks within methods to be two levels deep, but allow a third level for catching exceptions (though other subscribers of course might set other limits).

Also, it should be possible to limit the nesting not just of code blocks but also of expressions within parenthesis.

3 Likes

We are normally quite cautious with these type of rules as we try to discourage an overly prescriptive approach, but this seems a valid point. So, what I am hearing is: nesting is not just a problem for IFs, the nesting rule should really detect nesting regardless ‘what block is nested into what block’. Also, you are suggesting an additional check on expression to catch invocations such as:

call1(call2(call2(call4())))

Is my understanding correct?

Exactly.

And, as not to be overly prescriptive, it could be configurable for:

  1. Levels of depth.
  2. What to allow exceptions for and how much extra room to give for those exceptions.
  3. Whether to include parenthetical expressions (or maybe this is a separate rule).
2 Likes

Checking for nested loops is a must, and often the reason for CPU Timeout errors.