Matthew Boston

Flat is better than nested

April 4, 2025

Key takeaway: When a function nests more than a level or two, return early on each failure case and extract named helpers.

Every level of nesting is more context the reader has to keep in their head, so flatten it. “Flat is better than nested” is from the Zen of Python, and it applies to any language.

Deep nesting buries the main purpose, mixes the happy path with the error cases, and makes inner branches hard to test, because you have to set up every condition above them to get there.

Guard clauses are the simplest fix. Here’s a function wrapping one real line in three conditions:

# shipping.py: before
def shipping_label(order: Order) -> str:
    if order.paid:
        if order.items:
            if order.address:
                return print_label(order.address)
            else:
                raise ValueError("order has no address")
        else:
            raise ValueError("order is empty")
    else:
        raise ValueError("order is unpaid")

Each error message is as far as it can be from its check. With guard clauses, each check sits next to its error and the real work is the last line:

# shipping.py: after
def shipping_label(order: Order) -> str:
    if not order.paid:
        raise ValueError("order is unpaid")
    if not order.items:
        raise ValueError("order is empty")
    if not order.address:
        raise ValueError("order has no address")

    return print_label(order.address)

Each early return also gets its own small sad-path test.

A few other tools do the same job. Pull a coherent nested block into a function, and let the name carry the meaning. Replace nested loops and conditionals with a map and filter pipeline. Replace a long if/else chain with a lookup table, so adding a shipping method is one line and an unknown one fails with a KeyError that names it.

Nested code is what comes out when you think through a problem in order: if this, then if that. Flattening means going back and reshaping it for the reader. That’s extra work, but skip it enough times and you end up with a function nobody wants to touch.