Why Pushing If‑Conditions Up and For‑Loops Down Boosts Code Quality
The article explains two simple yet powerful rules—"Push Ifs Up" and "Push Fors Down"—showing how moving condition checks out of functions and placing bulk processing loops later can reduce duplicated checks, improve readability, and unlock performance gains.
Push If Conditions Up
Many developers wonder whether a conditional check belongs inside a function or should be performed by the caller. Moving the
iftest to the caller eliminates repeated pre‑condition checks, keeps the function focused on its core work, and reduces branching inside loops, making the code easier to read and less error‑prone.
<code>// Good example
fn frobnicate(walrus: Walrus) {
...
}
// Bad example
fn frobnicate(walrus: Option<Walrus>) {
let walrus = match walrus {
Some(it) => it,
None => return,
};
...
}</code>By handling invalid arguments early, the function body stays clean, and duplicated checks across the codebase disappear. Centralising the
iflogic also makes dead code easier to spot.
Push For Loops Down
This rule stems from data‑oriented programming: process collections in bulk rather than one element at a time. When a hot path works on many items, moving the loop to the outer layer lets the inner code focus on the per‑item operation, enabling vectorisation and reducing overhead.
<code>// Good example
frobnicate_batch(walruses);
// Bad example
for walrus in walruses {
frobnicate(walrus);
}</code>Combining both rules—checking conditions before the loop and iterating after the check—produces clearer control flow and opens the door to further optimisations such as batch processing, SIMD, or parallel execution.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.