Read the Code You Accept
The assistant has written the function that saves Kitty's expenses. It runs, the list fills up, and you are tempted to move on. But you have not read it, and code you have not read is code you are only hoping about. Reading generated code is a skill with a fast, repeatable method.
The rule
Read for shape, trace one real input, question every line you can't explain.
Here is the function the assistant wrote:
def add_expense(db, flat_id, paid_by, rupees, note):
amount_paise = int(float(rupees) * 100)
db.execute(
"INSERT INTO expenses (flat_id, paid_by, amount_paise, note) "
"VALUES (?, ?, ?, ?)",
(flat_id, paid_by, amount_paise, note),
)
db.commit()Read it in three passes:
- Shape. Which files and functions changed, and what does each name promise? Here: one function that stores an expense. The name matches. Thirty seconds.
- Trace. Follow one real input through, line by line, writing down the values. What arrives, what gets stored, what comes back out?
- Question. Any line you cannot explain, ask about. Then check the answer against the code itself, and the documentation if needed, instead of simply believing it.
Reading also shows you what is done well. The ? placeholders keep the note separate from the SQL text, which is the safe way to build a query. You will see why in the security section.
The shortcut
When you trace, always use two inputs: an ordinary one and an awkward one. Ordinary inputs show the code works; awkward ones show where it doesn't.
Shape
One function, one job: convert rupees to paise and store a row. Nothing unexpected.
Notice that nothing crashed. The code ran, the page looked right, and the stored number was wrong. Only tracing an awkward input revealed it.
Drills
Answer fast — trust the rule.
What is the first pass when you read a change?
In Python, what does int(19.99 * 100) give?
Why trace an awkward input as well as an ordinary one?
The assistant explains a line you did not understand. What next?
What does the ? in VALUES (?, ?, ?, ?) do in this code?
Remember
- Rule: read for shape, trace one real input, question every line you can't explain.
- Shortcut: trace two inputs, an ordinary one and an awkward one.
- Trap: code that runs and looks right while storing the wrong value.
