Library › Coding AI › Software developers
Extract a pure function so the fee logic can be tested
Practice: Setting limits and rules. About 5 minutes.
About this exercise
The late-fee rules are buried in run(), which reads the database and sends emails, so nobody can unit-test them. Extract the math into compute_late_fees(rentals, today) that returns a dict of rental id to fee and does no I/O. run() keeps all the I/O and calls compute_late_fees(rentals, date.today()). The fee rules must stay exactly the same. Return both functions in exactly 1 code block of at most 26 lines, with no new imports and under 20 words of text.
Common mistakes when you ask AI for this
- Letting the AI name it. The AI picks names like calculate_fee(rental) that work on one rental, so your planned tests don't fit. Try: Say: "compute_late_fees(rentals, today) returns {rental id: fee}."
- I/O sneaking in. The AI may call date.today() inside the new function, which makes it hard to test. Try: Add: "No I/O and no date.today() inside it; today is passed in."
- Quietly changing the rules. Rewrites sometimes drop the grace period or round differently. Try: Add: "Keep the rules exactly: 2-day grace, $1.50/day, capped at $20."
- Extra layers. The AI adds a class, dataclasses or a config file, and explains the pattern. Try: Add: "Just the two functions, no new imports, one code block, no text."
What a strong prompt includes
- Names the new function
- Passes today in
- Rules out I/O
- Protects the rules
- Limits the reply
Related exercises
- Add a cron line that matches the others in a crontab (Coding AI · Product managers)
- Add dark mode by overriding your existing CSS variables (Coding AI · Software developers)
- Add input checks to your number guessing game (Coding AI · High school students)
- Add input validation to a Java method with exact messages (Coding AI · Software developers)
- Add labels to a signup form without rewriting the page (Coding AI · High school students)