A senior code review of a 300-line order method: ranking findings by severity (double charges, partial writes, swallowed errors, hidden time), writing kind and specific review comments, and a safe step-by-step plan to make it readable.
I'd review it by severity, not by line order. The 300 lines are the least of the problems: the method charges the card before saving the order with no idempotency key, so a timeout and retry can double charge and a crash after charging leaves money taken with no order. It sends email inline and swallows exceptions with an empty catch, so failures vanish. It reads DateTime.Now and multiplies by a magic 1.1.
Those are blocking comments. Readability is a suggestion with a plan: first add characterisation tests, then make small behaviour-preserving PRs (guard clauses, Extract Method per step, then Extract Class per responsibility), keeping correctness fixes in separate PRs. The trade-off is speed: a big-bang rewrite looks faster but hides behaviour changes in a diff nobody can review.
"I'd start by reading the whole method once without commenting, to understand the flow, and then rank what I find by how bad it is in production rather than going line by line. In a method like this the length is a symptom; the serious issues are usually in the ordering of side effects. Here the card is charged before the order is saved and there's no idempotency key, so a client retry after a timeout can charge twice, and a crash between charge and save means we've taken money with no order. That's a blocking comment, and I'd suggest saving the order as pending first, charging with the order id as the idempotency key, then confirming.
For example, at [company] we had [a checkout method like this] and I [found the same charge-before-save ordering during a review]. Rather than asking the author to rewrite it all, I left two blocking comments for the payment ordering and the swallowed exception, and offered a plan for the readability part: characterisation tests first, then extract each step into a well-named method in small PRs. We [paired on the first PR]; the method went from [300] lines to a [25]-line orchestration over [four] weeks and [duplicate-charge tickets dropped to zero].
The mistake I see in reviews like this is either nit-picking formatting on a method with a double-charge bug, or demanding a full rewrite in one PR. I separate 'must fix before merge' from 'let's improve this over the next few PRs', and I keep refactoring PRs separate from behaviour-change PRs so each is reviewable."
public async Task<Guid> PlaceOrder(OrderRequest req)
{
if (req != null) { // 1
if (req.Lines != null && req.Lines.Count > 0) {
decimal total = 0;
foreach (var l in req.Lines) {
var p = _db.Products.First(x => x.Sku == l.Sku); // 2
total += p.Price * l.Qty;
}
if (req.Country == "AU") total = total * 1.1m; // 3
if (DateTime.Now.Hour < 9) total = total * 0.95m; // 4
var charge = await _payments.ChargeAsync(req.CardToken, total); // 5
var order = new Order { Id = Guid.NewGuid(), Total = total, ChargeId = charge.Id };
_db.Orders.Add(order);
_db.SaveChanges(); // 6
try {
await _email.SendAsync(req.Email, BuildBody(order)); // 7
} catch (Exception) { } // 8
return order.Id;
}
}
return Guid.Empty; // 9
// ... ~250 more lines of stock reservation, loyalty points and audit logging
}
| # | Severity | Finding | Suggested fix |
|---|---|---|---|
| 5, 6 | Blocking: money | Charge before save, no idempotency key. Retry = double charge; crash after charge = no order | Save order as PendingPayment, charge with order.Id as idempotency key, then mark Paid |
| 8 | Blocking: lost failures | catch (Exception) { } swallows email failures silently |
Log with ILogger, and move email to an outbox / background job |
| 6 | Blocking: thread pool | Sync SaveChanges and First in an async method; no CancellationToken |
SaveChangesAsync(ct), FirstAsync(ct) or one batched query |
| 2 | Wrong data / perf | N+1 query per line; First throws an unhelpful exception for an unknown SKU |
Load all SKUs in one query; return a validation error for unknown SKUs |
| 3, 4 | Wrong data | Magic GST rate; DateTime.Now is server-local (UTC in Azure), so the 'before 9am' discount fires at the wrong time |
Named GstRate, inject TimeProvider, convert to the customer's time zone |
| 9 | Diagnostics | Invalid input returns Guid.Empty instead of an error |
Throw/return a validation result; let the endpoint map it to 400 ProblemDetails |
| 1 | Readability | Arrow-shaped nesting | Guard clauses |
| all | Design | Six responsibilities in one method | Extract method per step, then classes |
namespace Shop.Orders;
public sealed class PlaceOrderHandler(
ShopDbContext db,
IOrderPricing pricing,
IPaymentGateway payments,
IOutbox outbox,
ILogger<PlaceOrderHandler> logger)
{
public async Task<Result<Guid>> HandleAsync(PlaceOrder command, CancellationToken ct)
{
if (command.Lines.Count == 0)
return Result<Guid>.Invalid("An order needs at least one line.");
var priced = await pricing.PriceAsync(command, ct);
if (priced.UnknownSkus.Count > 0)
return Result<Guid>.Invalid($"Unknown products: {string.Join(", ", priced.UnknownSkus)}");
var order = Order.CreatePending(command.CustomerId, priced.Total);
db.Orders.Add(order);
await db.SaveChangesAsync(ct); // order exists before money moves
var charge = await payments.ChargeAsync(
command.CardToken, priced.Total, idempotencyKey: order.Id.ToString(), ct);
order.MarkPaid(charge.Id);
outbox.Add(new OrderConfirmed(order.Id, command.Email)); // email sent by a background worker
await db.SaveChangesAsync(ct);
logger.LogInformation("Order {OrderId} placed for {Total}", order.Id, priced.Total);
return Result<Guid>.Ok(order.Id);
}
}
ChargeAsync runs twice and the customer pays twice. Could we save the order as pending first and pass order.Id as the idempotency key? Happy to pair on it."OrderPricing, time-zone-aware discount.CancellationToken), CA1031 (don't catch general exceptions) and Sonar cognitive-complexity on new code so the next review doesn't need these comments.Checks that the candidate reviews for production impact first, plans a safe incremental refactoring, and gives feedback that a colleague can act on without feeling attacked.
Green flags
Red flags
Reviewers have limited attention and authors have limited patience. Leading with formatting comments on a method with a double-charge bug buries the one comment that matters. A useful order:
1. Crash, stall, security hole, money or data loss
2. Wrong results (rounding, time zones, edge cases)
3. Diagnostics (logging, error responses, observability)
4. Design and readability
5. Style (ideally automated away)
Any method that touches more than one system (database, payment provider, email) has a partial failure problem: there is no transaction across them.
Bad: charge ──► save ──► email
│ crash here = money taken, no order
Good: save(pending) ──► charge(idempotencyKey=orderId) ──► save(paid + outbox row)
│
background worker └──► email
The idempotency key makes a retried charge return the original result instead of charging again (Stripe and most gateways support this). The outbox pattern writes the 'send email' intent in the same database transaction as the order, and a worker delivers it at least once.
Michael Feathers' approach for legacy code: characterisation tests capture what the code does today, right or wrong. Then each refactoring is checked against them.
ifs; pure structural change.ValidateAsync, PriceAsync, ChargeAsync, SaveAsync, NotifyAsync.A diff that both moves code and changes it is almost impossible to review: the reviewer can't tell which lines changed meaning. Keeping them apart means refactoring PRs can be approved quickly ("tests unchanged, all green") and behaviour PRs get the attention they need.
A good comment has: what (the issue), why (the consequence), a suggestion, and a label (blocking / suggestion / nit). Conventional Comments is a common format. Ask questions when unsure: "Is the empty catch intentional? If email fails we won't know."
Characterisation test first (pins today's behaviour), then the first safe refactoring step.
// Step 0: characterisation test around the legacy method, using fakes for the payment and email side effects.
namespace Shop.Orders.Tests;
public class PlaceOrderCharacterisationTests(SqliteShopFixture fixture) : IClassFixture<SqliteShopFixture>
{
[Fact]
public async Task Australian_order_before_9am_is_charged_with_gst_and_early_discount()
{
var payments = new FakePaymentGateway();
var service = fixture.CreateLegacyOrderService(payments, new FakeEmailSender());
var id = await service.PlaceOrder(new OrderRequest
{
Country = "AU", CardToken = "tok_test", Email = "[email protected]",
Lines = [new("SKU-1", 2)]
});
// Snapshot captures the charged amount, saved order and email call exactly as today.
await Verify(new { id, payments.Charges, Order = await fixture.FindOrderAsync(id) });
}
}
// Step 1: guard clauses only. Behaviour identical; tests unchanged and green.
public async Task<Guid> PlaceOrder(OrderRequest? req)
{
if (req?.Lines is not { Count: > 0 })
return Guid.Empty; // unchanged for now; switching to a validation error is a separate behaviour PR
var total = await CalculateTotalAsync(req); // Step 2: Extract Method
var charge = await _payments.ChargeAsync(req.CardToken, total);
var order = SaveOrder(total, charge.Id);
await SendConfirmationAsync(req.Email, order);
return order.Id;
}
The senior move in this review is recognising that length is the symptom and ordering of side effects is the disease. A junior reviewer comments on nesting; a senior asks what happens if the process dies between line 5 and line 6. The second senior move is social: blocking only on what truly must change, offering a plan and help for the rest, and turning repeated feedback into tooling so reviews stay about design.
Measure the outcome: method cognitive complexity in Sonar before and after, defect tickets tied to the area, and review turnaround for PRs touching it.
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
| Block on correctness, plan the rest | Most reviews of legacy code | A follow-up ticket | Never skip correctness |
| Pair on the first refactoring PR | Author is junior or unfamiliar with the technique | An hour or two of senior time | Author is experienced and keen to own it |
| Big-bang rewrite | Almost never; behaviour fully specified by tests | High risk, unreviewable diff | Money-handling code without tests |
| Leave it long | Code is stable and rarely changed | None | It is a hotspot with frequent changes |
Small is not a line count. A method is the right size when it works at one level of abstraction: it reads like a list of steps, each step named, with the details pushed into well-named helpers. A class is the right size when it has one reason to change and its fields are used together (high cohesion).
Split when a method mixes business steps with plumbing, when you feel the need for section comments, or when a class's fields fall into groups used by different methods. Don't split when the extracted piece has no better name than the code itself, or when the reader would have to jump through five two-line methods to follow one simple flow. The trade-off is locality versus abstraction: every split hides detail but adds a jump.
I treat a large refactoring as a series of small, behaviour-preserving steps merged to main continuously, not a big-bang branch. First I pin current behaviour with characterisation tests. Then I pick a technique: strangler fig to route traffic piece by piece to a new implementation, branch by abstraction to put an interface in front of the old code and swap implementations behind it, or parallel change (expand, migrate, contract) for APIs and database schemas. Feature flags and shadow comparisons let old and new paths run side by side. I prioritise hotspots (code that changes often and hurts), keep refactoring commits separate from feature commits, and define an end state so it does not drag on forever.
A side effect is any observable change a method makes besides returning a value: writing to a field, the database, a file, a queue. It is hidden when the method's name and signature don't tell you, like a GetCustomer that also updates LastSeenAt.
Three tools keep effects visible:
Task CancelOrderAsync); a query returns data and changes nothing (Task<Order?> GetOrderAsync).CalculateRefund(order, now) with now coming from an injected TimeProvider (in UTC) instead of DateTime.Now inside.init setters and immutable collections so callers can't change your state behind your back.The trade-off: some APIs legitimately combine both (Stack.Pop, TryDequeue, Interlocked.Increment) because atomicity matters, so the rule is make effects obvious, not ban them.
How to tell it (STAR)
**S:** Our checkout had a [300]-line method and customers were being charged twice [a few times a week]. **T:** I picked up the review of a change to that method and was asked to find the cause. **A:** I spotted that it charged the card before saving the order with no idempotency key; I left that as a blocking comment with a suggested fix and shipped an idempotency key and a reconciliation job that week. Then, instead of a rewrite, I agreed a plan with the author: characterisation tests, then small extract-method PRs, then reordering with an outbox, and we paired on the first one. **R:** Duplicate charges went to [zero], the method became a [25]-line orchestration over [four] weeks, and review time for checkout PRs dropped from [days] to [hours].
Last updated 23 Nov 2026.