📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Code review: an order service has a single 300-line PlaceOrder method that validates input, calculates prices and GST, writes to the database, charges the card and sends a confirmation email. How would you review it, and how would you make it readable step by step without breaking anything?

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.

Senior CodeReview Advanced clean-code code-quality code-review long-method order-service refactoring

🎯 Key points

  • Rank findings by severity: double charge / partial write first, then wrong data, then diagnostics, then readability
  • No transaction spans the database, the payment provider and email: persist a pending order first, charge with the order id as idempotency key, then confirm
  • Email sent inline with failures swallowed by catch (Exception) {}; move it to an outbox and log failures
  • Sync SaveChanges and an N+1 First() per line inside an async method: use SaveChangesAsync(ct) and load all SKUs in one query
  • Hidden inputs: DateTime.Now (server time, UTC in Azure) and a magic GST 1.1
  • Characterisation tests pin what the code does today, bugs included (e.g. Verify snapshots of the saved order and captured charges), before any restructuring
  • Then small behaviour-preserving PRs (guard clauses, Extract Method, Extract Class), with correctness fixes in separate labelled PRs
  • Each comment states what, why and a suggestion, labelled blocking or suggestion, and repeated feedback becomes analysers (CA1031, CA2016)

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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."


Code under review

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
}

Findings, ranked by severity

# 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

The rewrite

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);
    }
}

How I'd close the review

  • Blocking (must fix before merge): payment ordering and idempotency; swallowed exception; sync DB calls. Each comment says what, why, and a suggested change, e.g. "If the client times out and retries, 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."
  • Suggestions (follow-up PRs, tracked in a ticket): guard clauses, extract steps, move pricing into OrderPricing, time-zone-aware discount.
  • Tooling: enable CA2016 (forward CancellationToken), CA1031 (don't catch general exceptions) and Sonar cognitive-complexity on new code so the next review doesn't need these comments.
  • Checklist: add 'external side effects are idempotent and ordered after persistence' to the team's PR template.

🔍 What the interviewer is checking

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

  • Spots charge-before-save and the missing idempotency key immediately
  • Ranks findings by severity and labels blocking vs suggestion
  • Insists on characterisation tests before restructuring
  • Separates refactoring PRs from behaviour-change PRs
  • Writes a kind, specific example comment

Red flags

  • Starts with naming and formatting
  • Proposes rewriting it all in one PR
  • Misses the swallowed exception or the payment ordering
  • Harsh or vague comment wording

📚 Learn in depth

1. Why severity order matters in review

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)

2. Ordering side effects

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.

3. Making a long method safe to change

Michael Feathers' approach for legacy code: characterisation tests capture what the code does today, right or wrong. Then each refactoring is checked against them.

  1. Characterisation tests at the method boundary (Verify snapshots of the saved order and outgoing calls captured with fakes).
  2. Guard clauses: invert the nested ifs; pure structural change.
  3. Extract Method per step with the IDE: ValidateAsync, PriceAsync, ChargeAsync, SaveAsync, NotifyAsync.
  4. Extract Class where steps have their own dependencies: pricing, payments, notifications.
  5. Fix behaviour in separate, labelled PRs (idempotency, time zone), each with a new test that failed before.

4. Why separate refactoring from behaviour change

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.

5. Kind, specific review comments

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."

Try it yourself

  1. Write a characterisation test for a long method using Verify, change one line deliberately, and see the snapshot diff.
  2. Use the IDE's 'Invert if' and 'Extract Method' on a nested method and check the tests stay green after each step.
  3. Simulate a payment timeout with a fake gateway that throws after charging, and observe the double charge without an idempotency key.
  4. Enable CA1031 and CA2016 on a project and count the findings.
  5. Rewrite three of your recent review comments in 'what / why / suggestion / label' form.

💻 Code

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;
}

⚠ Common mistakes

  • Mistake: Reviewing line by line and leaving 30 comments of equal weight. Why it is wrong: the double-charge bug gets lost among nits. Instead: rank by severity and label each comment blocking, suggestion or nit.
  • Mistake: Asking the author to rewrite the whole method in this PR. Why it is wrong: a 300-line rewrite can't be reviewed and hides behaviour changes. Instead: block only on correctness, and agree a plan of small follow-up PRs.
  • Mistake: Refactoring without characterisation tests. Why it is wrong: nobody knows what the method currently does, so nobody can tell if it changed. Instead: pin current behaviour first, bugs included.
  • Mistake: Mixing refactoring and bug fixes in one PR. Why it is wrong: reviewers can't tell moved lines from changed ones. Instead: separate, labelled PRs.
  • Mistake: Calling a payment provider before persisting the order, without an idempotency key. Why it is wrong: retries and crashes cause double charges or orphaned payments. Instead: persist pending, charge idempotently, then confirm; use an outbox for follow-on effects.
  • Mistake: Writing comments like "this is messy" or "why would you do this?". Why it is wrong: vague and personal, so they create defensiveness and no action. Instead: state the consequence and a concrete suggestion, and offer to pair.
  • Mistake: Leaving the same comments review after review. Why it is wrong: it is slow and feels personal. Instead: encode them as analysers (CA1031, CA2016) and PR template items.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate talks about extracting methods and classes Why: Checks they know when splitting helps and when it over-fragments the code
    How to answer

    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.

  2. When: Candidate proposes a multi-week refactoring plan Why: Checks they can run a large refactoring while features keep shipping
    How to answer

    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.

  3. When: Candidate mentions DateTime.Now or ordering of side effects Why: Checks they can separate pure decisions from side effects
    How to answer

    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:

    • Command-query separation: a command changes state and returns nothing (Task CancelOrderAsync); a query returns data and changes nothing (Task<Order?> GetOrderAsync).
    • Pure functions: output depends only on input, so CalculateRefund(order, now) with now coming from an injected TimeProvider (in UTC) instead of DateTime.Now inside.
    • Immutability: records, 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.

🛠 Real-world problems: how you handle them

Duplicate card charges traced to a 300-line checkout method
Situation
A checkout service at [company] processing [N] orders a day through a single [300]-line `PlaceOrder` method. Payment provider in Stripe test mode in staging, live in production.
Signals
Support tickets for duplicate charges [a few per week]; payment provider dashboard showing charges with no matching order; App Insights showing client retries on `POST /orders` after [~30 s] timeouts during peak.
Investigation
Matched charge ids in the provider export against the `Orders` table to find orphaned charges; traced a duplicate in Application Insights and saw two POSTs with the same basket; read the method and found charge-before-save with no idempotency key and a swallowed email exception.
Resolution
Immediately: added an idempotency key derived from the basket id to the charge call and a nightly reconciliation job to refund orphans. Then: characterisation tests, guard clauses and Extract Method in small PRs, and finally pending-order-first ordering with an outbox for confirmation emails.
Prevention
Reconciliation alert when provider charges and orders diverge; CA1031 and CA2016 as warnings; PR template item about idempotent external calls; integration test that simulates a timeout after charging.

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].

↩ Usually asked after

More in Clean Code

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me