Skip to content

Hand-built counters and flag loops ​

Code longer than it needs to be: one of the ways AI coding agents bloat software, from lessloc's pattern catalog. lessloc catches it as simpler.

What makes hand-built counters and flag loops a bad practice? ​

The standard that calls it a bad practice: Fowler: Replace Loop with Pipeline.

What does lessloc do about hand-built counters and flag loops? ​

lessloc catches it as simpler.

  • simpler (tier 2): Brute-force code with a shorter idiom: == True, an if/else that returns the condition, an index loop that only reads xs[i], .filter(...).length > 0, a catch that only rethrows, a flag loop that is any(), a hand-built counter, an __init__ that @dataclass writes, a React Effect that only sets state. ruff and clippy add more.

Examples ​

Caught as simpler:

python
def has_refund(orders):
    found = False
    for order in orders:
        if order.refunded:
            found = True
            break
    return found

Written well:

python
def has_refund(orders):
    return any(order.refunded for order in orders)

Caught as simpler:

python
def tally(words):
    counts = {}
    for w in words:
        if w in counts:
            counts[w] += 1
        else:
            counts[w] = 1
    return counts

Written well:

python
from collections import Counter


def tally(words):
    return Counter(words)

The other patterns in Code longer than it needs to be:

Released under the Apache-2.0 license. · llms.txt