Skip to main content

Find where the rule lives

Level 5: Judging Code You Did Not Writemedium24 mincode readingtracingcode reviewminimal change

Trace one reported symptom across a small service to the duplicated business rule that drifted, then fix it in the layer that owns it.

A repo is not a snippet

Up to now every exercise in this level fit in one file. This module hands you a small codebase instead: a file tree, a README that is the bug report, read-only modules you must not touch, and a test suite that is part of the code you are judging. The habits are the ones you already built, they just start one step earlier, because first you have to find the code worth judging. Before you edit anything, read the README, then the tests, then the files they point at.

Follow the symptom, not the file

The report in this lesson says two surfaces disagree: the cart preview shows one shipping price and the checkout summary shows another for the same cart. The reflex is to open the screen named in the report and nudge its math until the numbers look right. Hold that reflex. A disagreement between two surfaces is evidence that one business rule is computed in more than one place, and you do not yet know which copy is wrong.

So trace before you edit. Start at each surface, follow its calls to the line where the disputed number is born, and search the repo for the rule's key constant. The pattern you are hunting looks like this, shown with a discount rule so the shipping trace stays yours to do:

# handlers/invoice.py
def invoice_total(subtotal_cents):
    if subtotal_cents >= 20000:      # inline copy of the discount rule
        return subtotal_cents - 2000
    return subtotal_cents
# billing/discounts.py
def apply_discount(subtotal_cents):
    """The documented home of the volume discount rule."""
    if subtotal_cents >= 25000:
        return subtotal_cents - 2000
    return subtotal_cents

One rule, two homes, two thresholds. Every symptom shaped like "screen A says one thing, screen B says another" ends at a fork like this one.

Check yourself
The cart preview and the checkout summary disagree about shipping for the same cart. What is your first move?

Decide which copy is the contract

Two copies disagree, so one is the rule and the other is an accident. The codebase usually tells you which. Look for the module whose docstring claims ownership, the copy with its own dedicated tests, and the function other layers already import. When those signals point at the same place, that place is the contract. The inline copy has no docstring, no tests of its own, and no caller besides the screen it sits in.

This is worth naming because generated code drifts exactly this way. An assistant shown one file at a time cannot see the helper it should have called, so it re-implements the rule inline, matching the surrounding style so well that the diff looks clean. Review passes. Then the next legitimate rule change updates the documented copy only, and two screens quietly start disagreeing.

Check yourself
You found two copies of the shipping rule and they disagree. How do you decide which copy is right?

Fix in the layer that owns the rule

The repair is not to make the inline copy correct. It is to make the inline copy stop existing. Delete the duplicated math and delegate to the owner:

# handlers/invoice.py, repaired
from billing.discounts import apply_discount


def invoice_total(subtotal_cents):
    return apply_discount(subtotal_cents)

This is the minimal change in the sense that matters. Correcting the inline threshold would fix one instance of the bug and keep the bug class. Delegating removes the class: with one computation left, the surfaces cannot disagree again no matter how the rule changes next.

Check yourself

Checkout carries an inline copy of the shipping rule that drifted. Sort each candidate fix by what it does to the duplicate.

Replace the inline math with a call to the pricing helper
Update the inline threshold so it matches the documented one
Copy the oversized branch into checkout as well

What to write down

A drift finding is only useful if the next reader can act on it. Three lines cover it:

  • Both sites: the documented rule and the inline copy, named by file and function.
  • The drift: which inputs the copies disagree on, with one concrete example.
  • The fix and its layer: delegate from the copy's site to the rule's owner, and why that direction.

Pitfalls

  • Patching the stale number where it sits. The copies match today and drift again on the next rule change.
  • Editing the canonical module to match the drifted copy. Now the healthy surface breaks, and its tests tell you so.
  • Delegating sideways instead of to the owner. Checkout can ask the cart preview for the number, and the two screens will agree, but the payment screen now depends on a browsing screen and inherits every change made for the cart's benefit.
  • Rewriting both layers into a new shared module when a one line delegation fixes the bug. Bigger diff, same behavior, more review risk.

Interview nuance: in a bug-fix round, saying "before I touch this, I want to know whether this rule is computed anywhere else" and then searching for the constant is a disproportionate seniority signal, because it shows you debug systems rather than lines. The quiet inline patch that makes the reported screen look right is the classic junior move, and interviewers seed drift bugs precisely to watch which one you reach for.

Check yourself
Next month the pricing team raises the free shipping threshold to 9900 cents in the pricing module. What happens to a checkout that kept its own inline copy of the rule?
Worked example (Python)
# Two homes for one discount rule. billing/discounts.py is the documented
# owner; handlers/invoice.py grew an inline copy that drifted.
DOCUMENTED_THRESHOLD = 25000
INLINE_COPY_THRESHOLD = 20000
DISCOUNT_CENTS = 2000


def documented_total(subtotal_cents):
    if subtotal_cents >= DOCUMENTED_THRESHOLD:
        return subtotal_cents - DISCOUNT_CENTS
    return subtotal_cents


def inline_total(subtotal_cents):
    if subtotal_cents >= INLINE_COPY_THRESHOLD:
        return subtotal_cents - DISCOUNT_CENTS
    return subtotal_cents


print("subtotal  documented  inline  agree")
disagreements = []
for subtotal in [15000, 19999, 20000, 22500, 24999, 25000, 30000]:
    doc = documented_total(subtotal)
    inline = inline_total(subtotal)
    if doc != inline:
        disagreements.append(subtotal)
    print(f"{subtotal:>8}  {doc:>10}  {inline:>6}  {'yes' if doc == inline else 'NO'}")

print()
print(f"The copies disagree from {disagreements[0]} to {disagreements[-1]} cents.")
print("Same rule, two homes. The drift zone is where customers see two prices.")

Apply

Your turn

The task this lesson builds to.

Fix orders/checkout.py so it takes its shipping figure from the documented rule in orders/pricing.py instead of computing one of its own, and so both surfaces agree for every cart, including oversized items. Start with README.md for the bug report. Do not modify the read-only files. Some tests are hidden.

3 hints and 3 automated checks are waiting in the workspace.

Practice

Make it stick

A second problem on the same idea, so it survives past today.

Your helpdesk's ticket list and ticket page disagree about which tickets are escalated. Find the copy of the escalation rule that drifted and repair helpdesk/ticket_list.py so both views agree with the documented rule in helpdesk/rules.py. Start with README.md for the bug report. Some tests are hidden.

3 hints and 2 automated checks are waiting in the workspace.