Read Code Fast
Lesson 2 Chunking
read words, not letters: the four-things working-memory limit
What you'll learn
- Group a long function into about four named chunks
- Find the seams between chunks: blank lines, comments, a change of subject
- Check the joins between chunks, where one step can fail after another succeeded
Your head holds about four things at a time. A 30-line function has far more than four. The fix is not to read harder, it is to group.
The idea
Working memory holds around four things at once. If you read a function one variable at a time, you overflow and lose the thread. Experienced readers don't read more carefully, they chunk: they group a few lines and give the group a name, like validate, price, save. Then they hold the names, not the lines.
Look for the seams: a blank line, a comment, a change of what is being worked on. A healthy function has about four chunks. If you count nine, the function does too much, and "split this up" is a fair review comment.
1def checkout(cart, user):2 if not cart["items"]:3 raise ValueError("Cart is empty")4 if not user.get("email"):5 raise ValueError("Email required")67 subtotal = 08 for item in cart["items"]:9 subtotal += item["price"] * item["qty"]10 tax = subtotal * 0.211 total = subtotal + tax1213 order = db.orders.insert(user_id=user["id"], total=total)14 db.carts.clear(cart["id"])1516 mailer.send(user["email"], f"Order {order.id} confirmed")17 return order
- Line 2 Chunk 1, validate: two guards. Read it as one idea: "bad input stops here".
- Line 7 Chunk 2, price: a sum, then tax. This is money, so it is the chunk to read closely.
- Line 13 Chunk 3, save: two writes to the database, one after the other.
- Line 16 Chunk 4, notify. The join between 3 and 4 is where to ask: if this fails, what is already done?
Take away
- Hold about four things: group lines into named chunks and keep the names.
- Find the seams: blank lines, comments, a change of subject.
- Check the joins between chunks: what is already done when the next one fails?
Quiz: test yourself
7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.