Code review series: 1. Goals, process and writing comments · 2. Resolving disagreements and worked reviews
Review usually fails in one of two ways: as a formality (approving a 1,500-line PR in two minutes) or as a battlefield (thirty comments about naming, a week-long argument). This post collects what it takes for review to be useful: goals, a checklist, the process, PR size, writing comments, and tooling. Part 2 covers handling disagreements, plus two worked reviews of real code from the course.
Related: Git and commit conventions for the author’s side; Clean code: naming, functions and control flow for what a reviewer looks at when judging readability.
1. What review is for
Key idea: to control quality and to let people on the team learn from each other. Review doesn’t replace tests, and it isn’t the place to impose personal taste.
- Quality control, at two levels:
- Product: bugs, security holes, behaviour that doesn’t match the requirement.
- Codebase: design, maintainability, consistency. Tests don’t measure these, but they decide how fast the team moves six months from now.
- Growing people. Hard skills: the reviewer learns code they didn’t know, the author learns better ways to do things. Soft skills: the author practises presenting a change, the reviewer practises giving feedback people actually want to hear.
A side effect: knowledge spreads. Every piece of code has at least two people who understand it, so one person’s holiday doesn’t stall the team (a higher “bus factor” — how many people the team can lose before the project stalls). Finding every bug is the job of tests and CI.
2. What to review: a checklist
Key idea: the course lists seven items: functionality, design, readability, consistency, tests, documentation, and calling out good things. For backends, add concurrency/transactions, failures and timeouts, security, performance, data compatibility, and observability.
Reading order matters just as much: the PR description (the goal) → the tests (the intended behaviour) → the design-heavy files (interfaces, entities, migrations) → the details. Reading in GitHub’s file order pulls you into details before you understand the whole.
The full Java/Spring checklist, with questions and examples
| Aspect | Questions | Backend example |
|---|---|---|
| Functionality | Does it do what was asked? Edge cases? | A 0-night booking, check-in today, guests equal to capacity |
| Design | Is it in the right layer? More complex than needed? | Business logic in the controller; an interface with one implementation |
| Readability | Can someone else understand it without asking? | A variable called aDays, a 200-line method, comments saying “what” instead of “why” |
| Consistency | Does it follow the repo’s conventions? | Response envelope, error codes, endpoint naming |
| Tests | Do tests check behaviour, including failures? | Happy path only; mocking the very thing under test |
| Docs | Do README, API docs or ADRs need updating? | A new endpoint missing from OpenAPI |
| Concurrency, transactions | What if two requests arrive at once? How far does the transaction reach? | SELECT ... FOR UPDATE without ORDER BY; an HTTP call inside a transaction |
| Failures and timeouts | What if a dependency is slow or down? | No timeout; retries that aren’t idempotent |
| Security | Is input validated? Is data exposed? | String concatenation into SQL; card numbers in logs; no ownership check |
| Performance | N+1, unindexed queries, loading whole tables? | findAll() then filtering in Java |
| Data and compatibility | Will the migration run on a large table? Do old API clients still work? | Adding a NOT NULL column without a default; renaming a JSON field |
| Observability | If it fails, are the logs and metrics enough to investigate? | catch (Exception e) {}; logs without a request id |
| Good things | Anything worth learning from? | A test reproducing a race condition; a very clear function name |
3. The process
Key idea: minor change → asynchronous peer review on the MR; major change → a group review session. The author carries most of the responsibility: self-review, write the description, assign reviewers only once CI is green. The same holds for code an AI agent wrote: the author verifies it before asking for review (working with AI coding agents).
Peer review needs one (or two) reviewers. Group review: the author walks the people affected through the design and the risky parts. For architectural changes, get a design doc approved before writing code, so the code review doesn’t turn into a design debate.
The course’s flow, paraphrased:
flowchart TD
A[Author finishes the feature/bugfix] --> B[Self-review the diff, write an MR description with context]
B --> C{CI build and tests green?}
C -- no --> A
C -- yes --> D{Major change?}
D -- no --> E[Assign reviewers: peer review]
D -- yes --> F[Schedule a group review]
E --> G[Reviewers read with a checklist, leave labelled comments]
F --> G
G --> H{Any blocking comments?}
H -- yes --> I[Author applies agreed fixes, answers every comment]
I --> G
H -- no --> J[Reviewer approves, merge]
The author:
- Re-reads the diff first. Most trivial issues (forgotten debug logs, stray files) get caught here.
- Writes a description: why, what changed, how it was tested, risks and rollback (template below).
- Assigns reviewers only once CI is green: nobody should read code that doesn’t compile.
## Why
Bookings get duplicated when clients retry (ticket BOOK-142).
## Changes
- Add UNIQUE(request_id) to the booking table (migration V42, index created CONCURRENTLY).
- The service returns the existing booking when it sees a known request_id.
## Testing
- Integration test: two parallel requests with the same request_id -> 1 booking, 2 identical responses.
- Ran the migration on a staging copy of the data: 38 seconds, no table lock.
## Risk and rollback
- Existing data had 12 duplicate request_ids: merged in V41. Rollback: drop the index; old code still works.
The reviewer: reads with the checklist and answers quickly. Google sets one business day as the upper bound for the first response; many teams aim for a few hours. Slow reviews push authors onto other work, force a context reload later, and encourage big PRs (“I’ll be waiting anyway”).
4. Change size
Key idea: small changes get reviewed faster and more carefully, and end up as better code. The slide says “Google: about 250 lines, keep it under 400”: the idea is right, but the figures are misattributed.
Ways to split a big change:
- Separate refactoring from behaviour changes. PR 1 renames, moves files, extracts methods (old tests still green); PR 2 adds the logic. PR 1 is quick to review: reviewers only check “nothing changed”.
- Stacked PRs: PR 2 is based on PR 1’s branch, each reviewed separately.
- Feature flags: merge parts while switched off, turn on when complete.
- Migrations on their own, using expand/contract: add the new column (expand), deploy code that writes both, backfill, switch reads to the new column, and only then drop the old one (contract). One PR per step.
- Generated changes (reformatting the repo, generated code, library upgrades) in their own PR, called out in the description.
5. Attitude and how to write comments
Key idea: the course’s three principles: be polite, contribute (offer a better way, not just point out what’s wrong), educate rather than criticise. And label every comment so the author knows which ones block the merge.
- Comment on the code, not the person: “what happens if this gets
null?” rather than “didn’t you think about null?”. - Explain why, with a link if there is one (docs, an article, an old bug).
- Offer an alternative, ideally as a code suggestion (GitHub/GitLab let the author apply it with one click).
- Ask when unsure: “my understanding is X, is that right?” often surfaces information the reviewer didn’t have.
- Praise specifically: not a courtesy, it tells the author what to keep doing.
| Label | Meaning | Blocks merge? |
|---|---|---|
TODO |
A real bug or risk; must be fixed | Yes |
NIT |
A small detail (naming, formatting) | No |
OPTIONAL |
A suggestion; the author decides | No |
FYI |
Information only; no action needed | No |
I add two more: QUESTION (needs an answer, not yet a change request) and PRAISE (something good).
Weak vs better comments, and Conventional Comments
| Weak comment | Better comment |
|---|---|
| “This is wrong.” | “TODO: this field isn’t final, so @RequiredArgsConstructor leaves it out of the constructor, Spring never injects it, and the first request NPEs. Suggest adding final.” |
| “Why not Optional?” | “OPTIONAL: returning Optional<Booking> forces callers to handle the missing case instead of forgetting a null check. Not required in this PR.” |
| “Terrible name.” | “NIT: aDays is a bit cryptic; would availableNights read better?” |
| (nothing about the good parts) | “PRAISE: the test that reproduces two parallel bookings is great, I’m going to reuse that approach.” |
6. Tooling: let machines say what machines can say
Key idea: anything a machine can check goes in CI, so humans can focus on design and behaviour. Block the merge on checks that are fast and certain; only warn on checks that need judgement.
| Kind (Spring Boot repo) | Tools |
|---|---|
| Formatting | Spotless with google-java-format or palantir-java-format, run in CI. Nobody comments on whitespace again. |
| Lint, static analysis | Checkstyle (conventions), Error Prone (wrong-type comparisons, ignored return values), SpotBugs and PMD (nulls, unclosed resources, broken synchronisation), SonarQube for aggregation and a quality gate |
| Architecture | ArchUnit: dependency rules written as tests |
| Dependencies, secrets | Dependabot or Renovate for upgrades; OWASP Dependency-Check or the platform’s scanner for CVEs; gitleaks to stop committed secrets |
| Tests, coverage | JaCoCo; coverage on the changed lines (diff coverage) is more useful than one number for the whole repo |
| Platform | CODEOWNERS to auto-assign reviewers by directory; branch protection (no direct pushes, green CI, N approvals); a PR description template |
An ArchUnit example: controllers don’t call repositories, plus a rule that catches exactly the bug in the worked review in part 2 (needs the archunit-junit5 dependency; not run for this post):
@AnalyzeClasses(packages = "com.example.booking")
class ArchitectureTest {
@ArchTest
static final ArchRule servicesUseFinalFields = fields()
.that().areDeclaredInClassesThat().areAnnotatedWith(Service.class)
.and().areNotStatic()
.should().beFinal()
.because("@RequiredArgsConstructor only injects final fields");
@ArchTest
static final ArchRule controllersDoNotTouchRepositories = noClasses()
.that().areAnnotatedWith(RestController.class)
.should().dependOnClassesThat().areAssignableTo(Repository.class);
}
Once the team has picked an architecture (layered, hexagonal, clean), write its dependency rules as ArchUnit tests instead of relying on reviewers’ eyes; sample rules for each style are in Codebase architecture.
Exercises
Exercise 1: Write labelled comments for a piece of code
Task: review the code below as if on a real MR: find the problems, label them, and write comments with consequences and fixes.
@RestController
@RequiredArgsConstructor
public class OrderController {
private final JdbcTemplate jdbc;
private final OrderItemRepository items;
private static final SimpleDateFormat FMT = new SimpleDateFormat("yyyy-MM-dd");
@GetMapping("/orders")
public List<OrderDto> search(@RequestParam String status, @RequestParam String from) {
try {
String sql = "SELECT * FROM orders WHERE status = '" + status + "' AND created_at >= '" + from + "'";
List<Order> orders = jdbc.query(sql, new BeanPropertyRowMapper<>(Order.class));
List<OrderDto> result = new ArrayList<>();
for (Order o : orders) {
result.add(new OrderDto(o.getId(), FMT.format(o.getCreatedAt()), items.findByOrderId(o.getId())));
}
return result;
} catch (Exception e) {
return List.of();
}
}
}
Answer to Exercise 1: seven labelled comments
- TODO: concatenating
statusandfrominto SQL is SQL injection (status=' OR '1'='1). UseJdbcTemplate’s?parameters (orNamedParameterJdbcTemplate), and parsefrominto aLocalDatein the controller so bad input is rejected with a 400. - TODO:
catch (Exception e) { return List.of(); }turns every failure (database down, a bug) into “no orders”, so neither users nor on-call know anything went wrong. Remove the catch and let the global handler return a 500 and log it (see Error handling in Spring Boot). - TODO:
SimpleDateFormatisn’t thread-safe, and here it’s astaticfield shared by every request: under load you’ll get wrong dates or exceptions. UseDateTimeFormatter(immutable and thread-safe) withjava.time. - TODO: calling
items.findByOrderIdin the loop is an N+1: 500 orders means 501 queries. Load all items in one query (WHERE order_id IN (...)) and group them with aMap. - TODO: no pagination and
SELECT *: a common status could return hundreds of thousands of rows. Add alimitwith a maximum and select only the needed columns. - NIT: query logic lives in the controller; move it to a service/repository so it can be tested on its own.
- QUESTION:
statusaccepts any string; is there a fixed list of valid values? If so, use an enum so Spring rejects unknown values.
Exercise 2: Split a 1,400-line PR
Task: a “pay with e-wallet” PR contains: renaming the payment package to billing (600 lines, all imports), a migration adding a wallet_transaction table, a client for the wallet API, a callback-handling service, a new endpoint, and reformatting of some old files. Propose a split.
Answer to Exercise 2: six stacked PRs
- A package-rename PR: renames only, no behaviour change; reviewed as “CI green, diff is only imports”.
- A separate formatting PR (or turn on Spotless for the whole repo in its own PR).
- A migration PR for the new table (unused yet, safe to deploy first).
- The wallet client + adapter + tests against a fake server (WireMock).
- The callback service + endpoint behind a disabled feature flag.
- A PR enabling the flag for a small group.
PR (4) onwards point back to the parent issue. Each PR stays under roughly 300 meaningful changed lines and can be reviewed in one short sitting.
Remember
- Can name the two goals of review and one thing review is not for.
- Know the order to read a PR in, and why reading only the diff isn’t enough.
- Can cite the PR-size figures correctly: Google (100 / 1,000 lines) and SmartBear at Cisco (~400 lines, 60–90 minutes).
- Can write a labelled comment with the consequence and the fix; know which labels block the merge.
- Know which checks to put in CI as blocking and which only as warnings.
Interview questions
Junior
What is code review for?
Quality control and growing people.
Quality covers bugs, security, design and maintainability of the codebase. People: reviewer and author learn from each other, and practise presenting and listening. Knowledge spreading through the team comes with it. Review doesn’t replace tests and isn’t the place to impose personal taste.
What do you do before sending a PR for review?
Self-review the diff, make sure CI is green, and write a description with enough context.
Remove debug code and run the tests. The description covers why, what changed, how it was tested, risks and rollback. Keep the PR small and focused on one thing; refactoring and formatting go in separate PRs.
What do the TODO, NIT, OPTIONAL and FYI labels mean in review comments?
TODO must be fixed before merging; NIT is a small non-blocking detail; OPTIONAL is a suggestion the author decides on; FYI is information only.
Labels tell the author which comments are merge conditions, and keep reviewers from accidentally blocking a PR over taste.
Mid
Reviewing a backend PR, what do you look at beyond “does it work”?
What happy-path tests don’t catch: concurrency, dependency failures, security, performance, compatibility and observability.
- Concurrency and transaction scope (two requests at once, side effects inside transactions).
- Failures and timeouts of dependencies.
- Security: input, authorisation, sensitive data in logs.
- Performance: N+1, missing indexes, no pagination.
- Compatibility: migrations on large tables, API changes.
- Logs and metrics; and whether the tests cover failure cases.
How big should a PR be, and why?
As small as practical: Google’s guide considers ~100 lines reasonable and 1,000 usually too large.
A SmartBear study at Cisco found defect detection drops once a review exceeds ~400 lines or 60–90 minutes. The exact number matters less than the principle: small PRs get careful, fast reviews; big PRs get skimmed.
A reviewer leaves 30 comments about naming and formatting. How do you fix that at team level?
Move whatever a machine can check into CI, and agree on labels so taste is a non-blocking NIT.
A formatter, Checkstyle, naming conventions in the contributing guide, all run in CI. Talk to the reviewer privately about focusing on design and behaviour. Formatting comments on PRs should all but disappear.
Senior
How do you keep code review from becoming the team’s bottleneck?
Small PRs, a measured response-time target, and automating whatever machines can do.
- A response target of a few hours, at most a business day, and track it.
CODEOWNERSto auto-assign and spread load; allow approving with NITs.- Pair with new joiners instead of many review rounds.
- For low-risk changes, allow merge-then-review.
- Measure PR cycle time so you see the problem instead of guessing.
Which rules do you put in CI to reduce reviewers’ work on a Spring Boot codebase?
A formatter, lint and static analysis, tests with diff coverage, dependency and secret scanning, and architecture rules in ArchUnit.
Concretely: Spotless, Checkstyle, Error Prone or SpotBugs. ArchUnit rules: controllers don’t call repositories, fields in @Service classes are final, the domain package doesn’t depend on web. Block on checks that are fast and certain; warn on ones that need judgement; fix flaky checks immediately.
Useful phrases for interviews
- “I review the description and the tests first, so I know what the change is supposed to do before I read the code.”
- “Every comment gets a label, so the author knows which ones block the merge.”
- “This is a TODO because the first request will hit a NullPointerException; here’s a suggested fix.”
- “Anything a machine can check, we check in CI, so humans can focus on design and behaviour.”
- “Smaller PRs get better reviews, so we split refactoring from behaviour changes.”
- “We aim for a first response within a few hours, and at most one business day.”
- “Google’s guide says about a hundred lines is reasonable; the four-hundred-line figure comes from the SmartBear study.”
- “Reading only the diff misses the call sites that should have changed too.”
Notes based on the Advanced Backend course (Ronin Engineer), rewritten in my own words.