Push ifs up and fors down: The idiom, its algebra, and its limits
The heuristic comes from TigerBeetle's Tiger Style document, which recommends centralizing control flow: when splitting a large function, keep all switch/if statements in the parent function and move non-branchy logic fragments to helper functions. The principle is often summarized as 'push ifs up and fors down': move conditional logic upward toward the caller or earlier in a pipeline, and push iterative loops downward toward batch processing or later in a tight, branch-free loop. This centralizes branching for clarity and can improve performance by leveraging bulk operations.
matklad's blog post illustrates both moves. Pushing conditionals up means that if a function branches on its input, consider moving that branch to the caller. For example, instead of frobnicate(walrus: Option<Walrus>) unpacking the option internally, the caller handles the None case and the function takes a plain Walrus. The function's type then states its precondition, narrowing the input state space and acting as a form of filtering; the key point is where the decision lives, not how much data flows downstream. Pushing loops down means deferring loops until after filtering or reducing the dataset, which minimizes unnecessary computations. Rather than calling frobnicate(walrus) in a loop, provide frobnicate_batch(walruses) and let the loop live inside it, so the hot loop runs without a branch and becomes a candidate for vectorization.
The two moves compose. Given a collection of Option<Walrus> values, the caller discards the Nones and unwraps the rest into a Vec<Walrus>, then hands that to frobnicate_batch, which never has to consider the None case at all. The excerpt gives this example: let maybe_walruses: Vec<Option<Walrus>> = ...; let walruses: Vec<Walrus> = maybe_walruses.into_iter().filter_map(|w| w).collect(); frobnicate_batch(&walruses); // never sees a None.
The post argues that the push-ifs-up-fors-down principle has far broader applications and explores perspectives from relational database query optimization, functional programming, and category theory. In SQL query planning, the same principle appears as performing projections and selections as early as possible and deferring joins or expansive operations until later, though the vocabulary runs upside-down: a query plan is a tree whose leaves are table scans and whose root produces the result, so data flows up from the leaves and the usual 'down' terminology is inverted. The excerpt cuts off as it begins to develop that database analogy.