CodeFaster

CodeFaster

Share this post

CodeFaster
CodeFaster
Faster if statements

Faster if statements

Faster to code of course

Tyler Adams's avatar
Tyler Adams
May 12, 2020
∙ Paid
3

Share this post

CodeFaster
CodeFaster
Faster if statements
Share

Faster (to code) if statements are much faster to read, debug, and modify than naively written if statements. What makes them so great?

  • explicit conditions

  • the if tree is “lean” and not “bushy”

  • A defensive else clause

Refactoring a slow if statement

Consider this (slow to code) if statement:

if foo:

    if bar < 4:

        if baz in ["a", "b", "k", "r"]:

            if qux:

                x = 0

            else:

                x = 1

        else:

            x = 2

    else:

        x = 3

else:

    x = 4

When is x = 2? Uh, well definitely when foo is true. Maybe when bar < 4? Not sure. So, um, if we look up from x = 2, it looks like “if baz in…” is lined up with it. So it’s when that’s not true. And before if baz…, both if foo and if bar < 4 are true, so… maybe x = 2 when

foo and bar < 4 and baz not in [“a”, “b”, “k”, “r”]

We’re right. But. Ew.

Avoid Bushy Decision Trees

Kernighan and Plauger agree. In The Elements of Programming Style, they have a rule: “avoid bushy decision trees”…

This post is for paid subscribers

Already a paid subscriber? Sign in
© 2025 Tyler Adams
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture

Share