Skip to content

Lesson 7 of 28Pull requests and code review

Giving Good Code Review

Review pull requests in the right order, find the bugs that matter, write comments people act on, and approve fast without lowering the bar.

21 min read0/4 questions

It is 10am and a teammate has tagged you on a pull request: "Add discount codes to checkout", 240 changed lines, CI green. You have half an hour before standup. You could skim it and type "LGTM", or you could leave 30 comments about naming. Neither helps. Code review is the main way a team keeps its codebase healthy and spreads knowledge, and it is a skill you get judged on from your first month. Done well, it catches the bug that would have cost a weekend and teaches both people something. Done badly, it slows everyone down and makes people dread opening a PR.

What review is for

A review has three jobs, in this order:

  1. Correctness. Does the change do what the ticket asks, without breaking anything else?
  2. Maintainability. Will the next person be able to understand and change this code?
  3. Shared knowledge. After the review, two people understand this part of the system instead of one.

It is not a gate where you make the code look like you would have written it. Google's public code review guide puts the standard plainly: approve a change once it clearly improves the overall health of the codebase, even if it is not perfect. There is no perfect code, only better code. If you hold every PR until it matches your taste, the team ships less and the code does not get better.

The flip side matters too. "Improves overall health" means you do not approve a change that makes things worse just because it works. A new copy of a helper that already exists, or business logic in a route handler, is a real cost that someone pays later.

Read in the right order

Most people open the "Files changed" tab and read from the top. That puts you in alphabetical order, not the order of the idea. Read like this instead:

Reading order for a pull request
  1. Description and ticketwhat problem, why now
  2. Testswhat behaviour is promised
  3. Core logicthe file the change is really about
  4. Wiringroutes, config, migrations
  5. Everything elserenames, imports, docs

Start with why. If you cannot say in one sentence what the PR is for, ask before reading code. You cannot judge a solution without knowing the problem.

1/4

For anything risky (money, auth, data migrations, concurrency), do not review from the browser alone. Check out the branch and run it:

gh pr checkout 482          # fetch the PR branch and switch to itgh pr diff 482 --name-only  # list the changed filespytest tests/checkout -q    # run the tests near the change

Ten minutes poking at the real behaviour finds things that an hour of reading will not.

Put it in order5 steps

You open a 240-line PR. Put your review steps in a sensible order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

What to look for

The Clean Code lesson gave a priority list for review comments. Here is what each item means when you are actually staring at a diff:

  • Design and fit. Is the logic in the right layer? Does it duplicate something that exists? Will the next similar feature slot in, or need a copy?
  • Behaviour and edge cases. Empty input, zero, negative numbers, very large values, None, the same request twice, two requests at once, a timeout halfway through.
  • Tests. Do they cover the failure path, not just the happy one? Would they fail if the bug you are worried about existed?
  • Security. Who is allowed to call this? Is user input reaching SQL, a shell, a file path or HTML? Did a secret or a debug flag sneak in?
  • Performance, only on hot paths: a query inside a loop, loading a whole table to count rows.
  • Readability. Could you understand this function from its name and signature?
  • Docs. Does a README, API doc or runbook now lie?

Leave formatting and import order to the formatter and linter. If you catch yourself writing the same style comment twice, propose a lint rule instead.

A real diff

Here is the core of the discount PR:

checkout/pricing.py
@@ -1,6 +1,15 @@
 from datetime import date
+from checkout.models import DiscountCode
 
 def order_total(items):
     return sum(i.price_pence * i.qty for i in items)
+
+
+def apply_discount(total_pence, code):
+    discount = DiscountCode.lookup(code.upper())
+    if discount is None:
+        return total_pence
+    if discount.kind == "percent":
+        return total_pence - total_pence * discount.value // 100
+    return total_pence - discount.value
checkout/routes.py
+@router.post("/carts/{cart_id}/discount")
+def add_discount(cart_id: int, body: DiscountIn, db: Session = Depends(get_db)):
+    cart = db.get(Cart, cart_id)
+    cart.total_pence = apply_discount(cart.total_pence, body.code)
+    db.commit()
+    return cart

The only test checks that SPRING10 takes 10% off 5000 pence. It passes. Before reading on, see how many problems you can spot. Then run the PR's logic against the cases a reviewer should try:

Python
from datetime import date # The PR's logic, with a dict standing in for the database.CODES = { "SPRING10": {"kind": "percent", "value": 10, "expires": date(2026, 6, 1)}, "TENOFF": {"kind": "fixed", "value": 1000, "expires": date(2027, 1, 1)},} def apply_discount(total_pence, code): discount = CODES.get(code.upper()) if discount is None: return total_pence if discount["kind"] == "percent": return total_pence - total_pence * discount["value"] // 100 return total_pence - discount["value"] # The PR's only test case:print("happy path:", apply_discount(5000, "spring10")) # The cases a reviewer tries:print("small basket:", apply_discount(500, "TENOFF"))print("applied twice:", apply_discount(apply_discount(5000, "TENOFF"), "TENOFF"))print("pasted with a space:", apply_discount(5000, " tenoff"))print("expired code:", apply_discount(5000, "SPRING10"))
Output
Press Run (⌘ Enter) to see what happens.

Every line after the first is a bug report. A fixed discount bigger than the basket gives a negative total. Calling the endpoint twice stacks the discount, because the route overwrites cart.total_pence with an already-discounted value. A code pasted with a leading space silently does nothing. Expiry is stored and never checked (the unused date import was a hint). And the route has two more: db.get returns None for a missing cart, which becomes a 500 error, and nothing checks that the cart belongs to the caller. Any logged-in user can discount anyone's cart by guessing an id. That last one is the most serious finding, and it is not in the "core logic" file at all.

Predict the outputPython

What does this print?

def apply_discount(total, value):
  return total - value

basket = 300
basket = apply_discount(basket, 250)
basket = apply_discount(basket, 250)
print(basket)
Need a nudge? Hints walk you through it.

Writing comments people act on

Finding the bug is half the job. The comment decides whether it gets fixed quickly or turns into a ten-message argument. Compare:

Bad:   This is wrong.
Bad:   Why didn't you check for negatives?
Good:  issue (blocking): a fixed code larger than the basket makes the total
       negative (TENOFF on a 500p basket gives -500). Stripe will reject a
       negative charge, but our order record would still say -500. Clamp at
       zero, and could we add a test for this case?

The good comment does four things: it says what is wrong, shows evidence (a concrete input and output), explains why it matters, and proposes a next step. It talks about the code, not the person. "Why didn't you" reads as an accusation even when you meant curiosity.

Labels tell the author how much each comment matters. The Clean Code lesson introduced Conventional Comments (issue, suggestion, question, nitpick, praise, with blocking or non-blocking). Use whatever prefix your team uses, but use one. Without it, authors treat every comment as a demand, or every comment as optional, and both are bad.

For small fixes, give the code itself. On GitHub, a suggestion block in a review comment on a line becomes a button the author can click to commit your change:

suggestion (non-blocking): strip whitespace too, people paste codes from emails.
 
```suggestion
    discount = DiscountCode.lookup(code.strip().upper())
```

Ask real questions when you are unsure, and mean them. "question: is there a reason this skips the expiry check? I may be missing where it happens." Sometimes the author knows something you do not, and a question leaves room for that without anyone losing face.

Praise specific good work: a clean test, a smart simplification, a migration that is safe to roll back. It is not fluff. It tells the author what to keep doing, and it makes your blocking comments easier to hear.

Match the pairs0/5 matched

Match each review comment to the label it should carry.

Choose an item, then its match on the other side.

Approve, comment, or request changes

GitHub gives you three verdicts, and each sends a signal:

  • Approve: this can merge. You can approve with non-blocking comments, which is what "LGTM with nits" means: fix them if you agree, no need for another round.
  • Comment: feedback without a verdict. Good for an early look at a draft, or when you only reviewed one part.
  • Request changes: something must change before merge. On repositories that require reviews, this blocks merging until you approve or someone with permission dismisses your review. So use it only for real blockers, and come back quickly when they are fixed.
gh pr review 482 --request-changes --body-file review.mdgh pr review 482 --approve --body "LGTM. Two nits, fix if you agree."

The discount PR gets Request changes: the authorisation hole and the stacking bug are blockers. A PR whose only problems are a naming preference and an optional refactor gets Approve with comments. Blocking on preference teaches people that review is about pleasing the reviewer.

Quick check
A PR fixes a real bug, has a good test, and works. You would have structured the helper differently and you spotted one variable name you dislike. What do you submit?
Need a nudge? A hint rules out a wrong answer.

Speed is part of quality

A PR waiting for review is work that is finished but delivers nothing, and the author either sits idle or starts something else and loses context. Google's guide says to respond within one business day at most, and teams that review faster ship faster. A good habit: check for review requests at natural breaks (after standup, after lunch, before you finish), not by dropping deep work every time a notification arrives.

If you cannot review properly today, say so: "I can look properly tomorrow morning. If it's urgent, ask Sam." A quick first pass that flags the one big design concern today is worth more than a perfect review on Friday. If the PR is too big to review well, say that too, and suggest how to split it. That is a fair comment, not an insult.

When to stop typing and talk

Some threads go back and forth five times without moving. That usually means you disagree about the design, not the line, and text is a bad medium for design. After two or three rounds, suggest a 15-minute call or a chat at the author's desk. Then write the outcome back on the PR: "Talked with Priya: we'll keep the service class, and add the cache in a follow-up (TICKET-913)." The PR is the record. The next person who wonders why will find the answer there, not in a call nobody remembers.

Reviewing AI-generated code

The AI on a Real Team lesson lists the typical smells in AI-assisted diffs. The reviewer's version is short: review the code, not how it was made, and check three things on purpose. Plausible but wrong APIs: a method or option that looks right but does not exist in the version in the lock file. Over-abstraction: a factory, an interface and a config option for something used once. Tests that agree with the code instead of testing it, which pass by construction. When in doubt, ask the author to explain a tricky block in their own words. That is a fair question on any PR.

Reviewing as a junior

You are not too junior to review. Read your teammates' PRs from week one: it is the fastest way to learn the codebase and the team's standards. Ask questions freely ("question: why does this need a lock? I'm learning this part"). Seniors expect it, and those questions sometimes expose a real gap. You will not be the last line of defence, so you do not need to approve alone, but you do need to say clearly what you checked: "Reviewed the pricing logic and tests; didn't look at the migration."

What senior reviewers do differently

They spend most of their time on the parts that are expensive to change later: data models, public API shapes, migrations, and anything that crosses a team boundary. A bad variable name costs a minute to fix next month. A bad column type costs a migration on a table with 200 million rows.

They also review the absence of things: the missing test, the missing metric, the missing feature flag, the missing rollback plan. A diff only shows what was added, so you have to ask what should have been there.

And they keep a sense of proportion. A hotfix at 2am gets a fast, focused review of the risky lines. A new service that everyone will build on gets a design review before any code exists.

Key terms
code health
How easy the codebase is to understand and change. Google's standard is to approve a change once it improves overall code health, even if it is not perfect.
blocking comment
A review comment that must be resolved before merge, such as a bug or a security hole. Everything else should be marked non-blocking.
Conventional Comments
A convention of starting review comments with a label (issue, suggestion, question, nitpick, praise) and an optional decoration such as blocking.
suggestion block
A GitHub review comment containing replacement code that the author can commit with one click.
request changes
A GitHub review verdict that blocks merging on repos with required reviews until the reviewer approves or the review is dismissed.
LGTM
Looks good to me. An approval, often with non-blocking nits the author can fix without another round.
idempotent
Safe to repeat: doing the operation twice gives the same result as doing it once. Applying a discount should be.