Push Ifs Up and Fors Down
Published on: 2025-07-03 21:31:55
A short note on two related rules of thumb.
If there’s an if condition inside a function, consider if it could be moved to the caller instead:
fn frobnicate (walrus: Walrus) { ... } fn frobnicate (walrus: Option ) { let walrus = match walrus { Some (it) => it, None => return , }; ... }
As in the example above, this often comes up with preconditions: a function might check precondition inside and “do nothing” if it doesn’t hold, or it could push the task of precondition checking to its caller, and enforce via types (or an assert) that the precondition holds. With preconditions especially, “pushing up” can become viral, and result in fewer checks overall, which is one motivation for this rule of thumb.
Another motivation is that control flow and if s are complicated, and are a source of bugs. By pushing if s up, you often end up centralizing control flow in a single function, which has a complex branching logic, but all the actual work is delegated to straight line subroutine
... Read full article.