TDD in the Age of LLMs#
Engineering vs LLMs#
LLMs can produce more code than anyone can read, review, test, or even comprehend; and this line has been crossed long ago with the industry still trying to catch up to the new reality. Software engineering has fundamentally changed, but that doesn’t mean we’ve lost it to LLMs. Software engineering has always been about filling the gap between business and technology, and this is the niche that LLMs cannot fully occupy without completely replacing humans on both ends. But how much of that niche can LLMs fill and where do the engineers fit in the new reality?
LLMs are able to solve long standing math problems. However, if it doesn’t result in evolving mathematical apparatus, the outcome is questionable. And I would argue the same for software development: using an LLM to implement a feature without evolving the domain model and knowledge doesn’t serve the business well. Software has a tendency to exponential complexity growth if model and abstractions aren’t managed carefully. It doesn’t matter that LLMs can handle 10x more compared to humans; if the complexity grows exponentially, it’ll hit a wall anyhow. In this new era, the human’s place becomes more focused on managing complexity and establishing a bridge between business and technology by managing the domain and abstraction. And this is where TDD still shines.
For over two decades, TDD has been one of the most powerful tools in software development. Its focus on breaking down the complexity of a codebase into abstractions with clear responsibilities mapped to the domain provides a way to express business rules through code while keeping complexity under control. In this article, I will try to evaluate test-driven development in the context of LLM-assisted coding. I use TDD as a broad term encompassing traditional TDD, BDD, ATDD, SDD, and DDD as they are practiced in the software development industry. While these approaches differ, they have one thing in common: they use the domain as a lens through which to scope and structure the code. I’ll share my experience and thoughts, along with some useful lessons learned as I’ll explore LLM-assisted TDD by working through the Supermarket Receipt Refactoring Kata.
Supermarket Receipt Refactoring Kata#
The Supermarket Receipt Refactoring Kata is a small supermarket checkout system that prices a cart, applies the week’s discounts, and prints a receipt. The kata starts with poorly structured code, no tests, and a high-level description of the expected behavior. The goal is to add new features while keeping the existing behavior intact. This makes it a great exercise for trying different LLM-assisted coding approaches.
One of the most tangled parts of the code is the discount logic. Here is the original code:
class ShoppingCart:
def handle_offers(self, receipt, offers, catalog):
for p in self._product_quantities.keys():
quantity = self._product_quantities[p]
if p in offers.keys():
offer = offers[p]
unit_price = catalog.unit_price(p)
quantity_as_int = int(quantity)
discount = None
x = 1
if offer.offer_type == SpecialOfferType.THREE_FOR_TWO:
x = 3
elif offer.offer_type == SpecialOfferType.TWO_FOR_AMOUNT:
x = 2
if quantity_as_int >= 2:
total = offer.argument * (quantity_as_int / x) + quantity_as_int % 2 * unit_price
discount_n = unit_price * quantity - total
discount = Discount(p, "2 for " + str(offer.argument), -discount_n)
if offer.offer_type == SpecialOfferType.FIVE_FOR_AMOUNT:
x = 5
number_of_x = math.floor(quantity_as_int / x)
if offer.offer_type == SpecialOfferType.THREE_FOR_TWO and quantity_as_int > 2:
discount_amount = quantity * unit_price - (
(number_of_x * 2 * unit_price) + quantity_as_int % 3 * unit_price)
discount = Discount(p, "3 for 2", -discount_amount)
if offer.offer_type == SpecialOfferType.TEN_PERCENT_DISCOUNT:
discount = Discount(p, str(offer.argument) + "% off",
-quantity * unit_price * offer.argument / 100.0)
if offer.offer_type == SpecialOfferType.FIVE_FOR_AMOUNT and quantity_as_int >= 5:
discount_total = unit_price * quantity - (
offer.argument * number_of_x + quantity_as_int % 5 * unit_price)
discount = Discount(p, str(x) + " for " + str(offer.argument), -discount_total)
if discount:
receipt.add_discount(discount)
The code has several smells and issues, including an incorrect total calculation caused by using / instead of // when calculating the number of qualifying offer groups:
total = offer.argument * (quantity_as_int / x) + quantity_as_int % 2 * unit_price
You may also rightly question why the ShoppingCart class is responsible for handling discounts, along with many other design decisions in the initial code. This is the core of the refactoring exercise. An LLM might be very helpful in spotting these smells and fixing design issues. However, there is a fundamental question: should we even consider these smells reasons to refactor the code in the first place, in the Age of LLMs?
A place in the loop#
I would argue that as long as we want to keep humans in the loop, we should treat these code smells and design issues as valid reasons to refactor, especially in the Age of LLMs, and be even more aggressive about it. TDD, in the broad sense, is a way of keeping the human in the loop while addressing the limits of complexity comprehension. The human’s role in the loop is to define abstractions and provide domain-driven scoping, while the LLM assists with the implementation.
Simply prompting an LLM to write tests before writing the code, or asking it to follow a TDD approach, removes the human from the “loop” and leaves the LLM responsible for the code’s design and architecture. This is not TDD. Just like running a team of agents, it’s a way to get code written faster, but it doesn’t necessarily develop deeper domain knowledge or expertise.
LLM-assisted Refactoring#
For this kata, I will follow these steps:
Understand the domain, and identify the business rules and the existing behavior.
Capture the existing behavior through high-level tests.
Refactor. Keep all existing tests passing.
Add new features.
Step 1: Understand the domain#
The ability of LLMs to process large amounts of text, explore an entire codebase, and provide a high-level overview of its design and business rules is extremely valuable, especially when working with unfamiliar or poorly documented legacy code.
However, this wasn’t always straightforward, nor always accurate. LLMs would often dump everything they had gathered into one large block of information, without organizing it around the domain, distinguishing important business rules from implementation details, or providing a coherent picture of how the system actually works. The challenge wasn’t so much gathering information as making sense of it.
What helped:
Breaking the exploration into smaller chunks focused on individual business rules, rather than asking for a complete codebase overview in one prompt.
Asking the LLM to identify business rules, domain concepts, and dependencies separately from implementation details.
Requesting concrete examples and tracing specific business scenarios through the code.
Challenging the results (“Are you really sure about that?”) and verifying important findings by hand.
Step 2: Pinning down existing behavior with tests#
LLMs tend to generate lots of low-level unit tests, often focusing on individual methods and implementation details, while overlooking the overall test structure and integration between components. 100% code coverage and 100% logical-case coverage aren’t the same thing, and LLMs overlooked that distinction several times.
What helped:
Identifying business scenarios, and asking the LLM to cover them with tests via a high-level interface.
Showing the test structure with an example, rather than just asking for it in a prompt.
Adding testing methods.
Splitting the presentation layer from the domain layer, and testing the domain layer first.
def test_ten_percent_discount() -> None:
toothbrush = Product("toothbrush", ProductUnit.EACH)
catalog = InMemoryCatalog()
catalog.add_product(toothbrush, 0.99)
teller = Teller(catalog)
teller.add_special_offer(SpecialOfferType.TEN_PERCENT_DISCOUNT, toothbrush, 10)
cart = ShoppingCart()
cart.add_item(toothbrush)
receipt = teller.checks_out_articles_from(cart)
assert receipt.to_dict() == {
"items": [
{
"product": "toothbrush",
"unit": "EACH",
"quantity": 1.0,
"price": 0.99,
"total_price": 0.99,
},
],
"discounts": [
{
"description": "10% off",
"product": "toothbrush",
"discount_amount": -0.099,
},
],
"total_price": 0.891,
}, "ten percent off should reduce the toothbrush line"
Step 3: Refactor. Keep all existing tests passing.#
This step is focused on improving the domain model and making the code reflect the business domain better. The goal is to make the code easier to understand and extend, so the human can be kept in the loop.
Similarly to how I used an LLM to explore the domain structure, I used it to build a new domain model. However, LLMs are not always reliable at understanding use cases or explaining how the different parts of the system fit together. LLMs tend to jump to conclusions and start implementing solutions before the problem and the domain model are properly understood or developed. The more advanced the LLM, the more eager it is to jump into writing a huge amount of code.
In practice, this often turned into a two-step, specification-driven development process: I used the LLM to work on domain design specifications.
When I was happy with the domain model, I moved on to the implementation-detail specifications.
## Product
Spec: an item with a name, sold by count or by weight. The price is not part of the product.
Responsibility: to identify something the shop sells. It does not know a price, an offer, a cart, or a receipt.
A frozen model:
- `name: str`
- `unit`: each or kilo
No methods. Callers read `product.name` and `product.unit`. It is frozen so the same product can be used as a key in the catalog.
What I learned about working with LLMs:
Premature implementation: LLMs tend to jump straight into coding, sometimes producing a lot of work in the wrong direction before the domain and requirements are clear.
Test drift: LLMs frequently modify existing tests to accommodate their implementation. This makes it easy to introduce slop or silently change the original expectations. Keeping the tests honest requires constant attention.
Domain understanding: LLMs can describe code structures, but often struggle to explain the business rules and tell a coherent story about how the system works.
Communication overhead: Explaining a design or desired change in natural language can be surprisingly difficult and time-consuming. Sometimes it’s easier to write a small prototype and let the LLM adapt it than to explain the intended structure in a prompt.
What helped:
Building the domain-model specifications step by step, rather than all at once.
Being explicit about preserving existing tests and their expectations. Never accepting a test change simply because it makes the implementation pass.
Writing small prototypes or examples to communicate design intent when words aren’t enough.
Frequently checking whether the implementation is moving in the right direction, rather than trusting the amount of work the LLM has produced.
Step 4: Add new features#
This was the most straightforward step in the end, even though it is the main focus of this post, because I had learned from the previous steps. I followed this workflow for LLM-assisted TDD:
Add specifications (Design / Domain). Identify where the feature belongs in the existing architecture/domain and create specifications for it.
Add high-level tests. Define acceptance criteria and write tests covering the main user flows and expected behavior.
Implement the feature. Work incrementally until the tests pass. Loop back to adding more tests when needed.
Adding new features didn’t reveal anything new compared to the previous steps. I used the LLM to help me understand the new features and determine the best way to implement them. I also used it to write tests and implement the features.
A few things I noticed again:
Premature implementation. Don’t let the LLM start coding before it has finished working on the specifications and tests.
Test drift. Don’t let the LLM modify or remove existing tests just to make them pass.
Communication overhead. It’s easier to just write code and point the LLM to it than to explain the intent in a prompt.