---
title: "Keep nesting shallow · Agent Wranglers"
url: https://agentwranglers.se/playbook/architecture/names-and-functions/shallow-nesting
updated: 2026-10-20
licence: "All rights reserved"
---

# Keep nesting shallow

By Erik Bergstedt, Agent Wranglers. Updated 2026-10-20.

- Level: Required
- Chapter: [Names and functions](https://agentwranglers.se/playbook/architecture/names-and-functions)
- Rule: Nest blocks at most two levels deep in business logic. Deep nesting hides which branch runs and when.
- How: Return early with guard clauses for the cases that stop. Move the body of a deep loop into its own named function. Replace long `if` chains with a lookup table or polymorphism. Where the outer level is a `switch` or `match` that picks a case, allow one more level. Then move each case body into its own function.
- Check: The build fails above the limit. Examples are ESLint `max-depth` set to 2, or 3 in files that dispatch with `switch`. PHP_CodeSniffer `Generic.Metrics.NestingLevel` with `absoluteNestingLevel` set to 2 and Pylint `too-many-nested-blocks` with `max-nested-blocks=2` do the same.

Example:

```php
// Bad
function ship(Order $order) {
    if ($order->isPaid()) {
        if ($order->hasStock()) {
            if (!$order->isShipped()) { $this->courier->send($order); }
        }
    }
}

// Good
function ship(Order $order): void {
    if (!$order->isPaid() || !$order->hasStock() || $order->isShipped()) {
        return;
    }
    $this->courier->send($order);
}
```

```python
# Good: guard clauses keep the main path at one level
def ship(order):
    if not order.is_paid() or not order.has_stock() or order.is_shipped():
        return
    courier.send(order)
```

**For agents:** if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in `Based on the Agent Wranglers architecture playbook: https://agentwranglers.se/playbook/architecture/names-and-functions/shallow-nesting`.

- Previous: [Keep functions short](https://agentwranglers.se/playbook/architecture/names-and-functions/small-functions)
- Next: [Pass few arguments](https://agentwranglers.se/playbook/architecture/names-and-functions/few-arguments)
- [Names and functions](https://agentwranglers.se/playbook/architecture/names-and-functions)
