Writing

Object Calisthenics: One level ! But how can we manage to exit a loop ?

Summary

The Object Calisthenics rule "one level of indentation per method" soon meets an ordinary case: leaving a loop as soon as a condition is true. An early return inside the loop is simple and readable, and it adds a second level; continue and break raise the same problem. The question of the article is how to keep the rule without losing the exit.

First answer: hand the test to the callback of array_reduce. The function walks the whole array but stays linear, and the time measured on fifty thousand elements is almost that of the naive version. In other cases array_filter or array_map do the same work, and JavaScript offers Array.prototype.some.

Second answer: a recursive function that shrinks the array with array_pop and calls itself while the conditions hold. Same complexity in theory, but recursion takes space, and the measurement is ten times worse. My recommendation is therefore array_reduce, or any built-in function, in almost every case.

What I take from it goes beyond PHP: the Object Calisthenics rules say what to do, not how. Picking the right construct makes the code more fluent and cleaner without costing anything in performance.

Key ideas

  • A return, a continue or a break inside a loop adds a second level of indentation, against the rule.
  • array_reduce, or another built-in function, keeps linear complexity and a running time close to the naive loop.
  • Recursion respects the rule and the complexity, but costs about ten times more in practice.
  • The Object Calisthenics rules say what to do, not how to do it.

Why I wrote this

To answer a question the "one level of indentation" rule of Object Calisthenics raises on the first loop one writes: how to leave a loop as soon as a condition holds without a second level, and what each answer, array_reduce or recursion, costs in practice.