Chapter 01
Can AI Generate Durable Code?
Can AI generate Durable Code? Yes, it can. Though, to borrow my wife’s favorite line, it takes patience and discipline.
Here is a function an agent wrote for me. I asked for each customer’s total spend since a given date. On the face of it the code is fine. It runs. If there were tests, they would pass.
def generate_spending_report(db, since):
customers = db.query("SELECT * FROM customers")
report = []
for c in customers:
orders = db.query(
f"SELECT * FROM orders WHERE customer_id = {c['id']} "
f"AND created_at >= '{since}'"
)
total = sum(o["amount"] for o in orders)
report.append({"name": c["name"], "total": total})
return report
Here is another version that AI generated with several adjustments.
def fetch_spend_totals(db, since):
return db.query(
"""
SELECT c.name, COALESCE(SUM(o.amount), 0) AS total
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.id AND o.created_at >= %(since)s
GROUP BY c.id, c.name
""",
{"since": since},
)
def build_report(rows):
return [{"name": r["name"], "total": r["total"]} for r in rows]
In this version, the query is parameterized, so a hostile since cannot inject SQL. It runs one query instead of one per customer, so it stays fast as the number of customers grows. And the shaping moved into its own function, which I can test with a couple of fake rows and no database. None of it was clever. It just needed me to decide which concerns mattered.
At scale
This is a small illustrative example. A real project has thousands of decisions like it, arriving faster than anyone could adjust by hand and most of them never as legible as this one.
Producing durable code across thousands of such calls asks three things of us.
- Having the right mechanisms, intuition, and experience to find the right depth to go to.
- To stay accountable for the breadth of these decisions touches across an organization.
- To build the systems that supply the judgment, context, feedback and gates at scale.