# Deep nesting

*Code longer than it needs to be*: one of the ways AI coding agents bloat software, from lessloc's [pattern catalog](https://lessloc.org/patterns/index.md). lessloc catches it as [`deep-nesting`](https://lessloc.org/guide/reference.md#tier-2).

## What makes deep nesting a bad practice?

The standards that call it a bad practice: [CWE-1124](https://cwe.mitre.org/data/definitions/1124.html) Excessively Deep Nesting; Sonar S134; Fowler: Replace Nested Conditional with Guard Clauses.

## What does lessloc do about deep nesting?

lessloc catches it as [`deep-nesting`](https://lessloc.org/guide/reference.md#tier-2).

- `deep-nesting` (tier 2): Statements nested 4 or more control levels deep.

## Examples

Caught as `deep-nesting`:

```python [ab.py]
def scan(rows):
    for r in rows:
        if r:
            for c in r:
                if c:
                    print(c)
```

Written well:

```python [ab.py]
def scan(rows):
    for r in rows:
        for c in r or []:
            if c:
                print(c)
```

## Related patterns

The other patterns in [Code longer than it needs to be](https://lessloc.org/patterns/index.md#code-longer-than-it-needs-to-be):

- [Brute-force idioms](https://lessloc.org/patterns/brute-force.md): lessloc catches it as `simpler`, built in for Python, JS/TS, Go, Rust, Java and C#. ruff (in every hook) and clippy (in `ci`) go deeper.
- [Hand-built counters and flag loops](https://lessloc.org/patterns/counters-and-flags.md): lessloc catches it as `simpler`.
- [A catch that only rethrows](https://lessloc.org/patterns/catch-rethrow.md): lessloc catches it as `simpler`.
- [A promise wrapped in new Promise](https://lessloc.org/patterns/promise-wrap.md): lessloc catches it as `simpler`.
- [Annotating types the compiler infers](https://lessloc.org/patterns/inferred-types.md): lessloc catches it as `simpler`.
- [A React Effect that only sets state from other values](https://lessloc.org/patterns/derived-effect.md): lessloc catches it as `simpler`.
- [Functions with many parameters (8 or more)](https://lessloc.org/patterns/long-params.md): lessloc catches it as `long-params`.
- [Long functions](https://lessloc.org/patterns/long-function.md): lessloc catches it as `long-function`.
- [If-chains on literal values](https://lessloc.org/patterns/if-chain.md): lessloc catches it as `if-chain`.
- [A file that keeps growing](https://lessloc.org/patterns/swollen-file.md): lessloc catches it as `swollen-file`.
- [Reformatting lines the task did not change](https://lessloc.org/patterns/churn.md): lessloc gives every session a rule against it and catches it as `churn`.
- [Net growth past a budget](https://lessloc.org/patterns/net-growth.md): lessloc catches it as `net-growth`.
- [Golfed code](https://lessloc.org/patterns/golfed-code.md): lessloc catches it as `clever` and `dense-lines`.
