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

📚 Interview question

Code review: you're reviewing a 250-line CustomerAccountService that handles sign-up, loyalty points, invoice emails and CSV export. Name every code smell you find, rank them, and tell me which you would ask to be fixed in this PR and which you would log as technical debt.

A code review exercise that names the smells in a realistic .NET service (god class, long method, primitive obsession, feature envy, duplicated code, hidden side effects, dead code), ranks them by severity, and separates must-fix-now comments from items logged as technical debt.

Senior CodeReview Advanced code-quality code-review code-smells csharp refactoring technical-debt

🎯 Key points

  • Rank by severity: correctness and security risks first (lost data, PII in logs), then wrong-data risks, then diagnostics, then design smells
  • Name each smell precisely (god class, long method, primitive obsession, feature envy, duplicated code, temporal coupling, dead code)
  • Fix-now rule: anything the PR introduces or makes worse, plus correctness/security issues
  • Debt rule: pre-existing design smells the PR doesn't touch go to the debt register with cost and trigger
  • Comments are kind and specific: smell name, why it matters, a concrete suggestion, blocking vs non-blocking label
  • Privacy Act 1988 / APP 11: personal information (email, DOB) in logs or exports is a must-fix; use log redaction (Microsoft.Extensions.Compliance.Redaction)
  • Ask for tests with each fix: a unit test pinning the single loyalty rule, an integration test that no email is sent when the save fails
  • Back recurring smells with analysers or architecture tests, not repeated comments

⏱ 30-second answer

I'd read it for risk first, style last. Ranked:

  1. Correctness/security: an email sent before SaveChangesAsync (customer told they're signed up when the save can fail), and personal information (email, date of birth) logged and exported unmasked, a Privacy Act issue.
  2. Wrong data: loyalty points calculated with duplicated, slightly different logic in two methods.
  3. Design smells: god class (four responsibilities), long method, primitive obsession (string email, Guid IDs), feature envy on Customer, dead code.

My rule: block on anything the PR introduces or touches that is a correctness or privacy risk; suggest small fixes in lines the PR changes; log as debt pre-existing structural smells with a ticket that says what they cost. The trade-off is merging safe code today without turning one PR into a rewrite.

🗣 Full answer (senior)

How I would answer this in an interview

"I review in severity order, not file order, because the author's time is limited and I want the comments that matter at the top. With this class, the first thing I'd flag isn't a smell at all: the welcome email is sent before SaveChangesAsync, so if the save fails the customer is told they have an account they don't have. That's a hidden side effect plus temporal coupling, and it blocks. Second, the logger writes the customer's email and date of birth, and the CSV export includes them without any access check or masking. Under the Privacy Act 1988 that's personal information leaking into logs we keep for [90] days, so it also blocks.

Then the wrong-data risk: loyalty points are calculated in SignUp and again in RecordPurchase, and one rounds down while the other rounds to nearest. That's duplicated code that has already diverged. If this PR touches either method I'd ask for one LoyaltyPolicy now; if not, it's a high-priority debt ticket. Below that are the design smells: the class is a god class with four reasons to change, SignUp is a long method, emails and IDs are raw strings and Guids, the tier calculation envies Customer, and there's an unused LegacyImport method. For example, at [company] I [reviewed a similar service] and [split my comments into two blockers and four follow-up tickets]; the PR merged [the same day] and the tickets were picked up [over the next two sprints].

My rule for the split is simple: block on correctness, security and privacy, and on anything the PR makes worse. Suggest improvements in lines the author is already changing. Log pre-existing structural smells as debt with what they cost and what would trigger fixing them. The mistake I see is the opposite: twenty nit comments about naming, nothing about the email sent before the save."


Code under review

public class CustomerAccountService(ShopDbContext db, IEmailSender email, ILogger<CustomerAccountService> logger)
{
    public async Task<Guid> SignUp(string name, string email, DateOnly dob, string? referralCode, CancellationToken ct)
    {
        logger.LogInformation("Sign-up for {Email} born {Dob}", email, dob);           // 1
        if (email == null || !email.Contains("@")) throw new Exception("bad email");    // 2
        var customer = new Customer { Id = Guid.NewGuid(), Name = name, Email = email, Dob = dob };
        await this.email.SendAsync(email, "Welcome!", "...", ct);                         // 3
        if (referralCode != null)
        {
            var referrer = await db.Customers.FirstOrDefaultAsync(c => c.ReferralCode == referralCode, ct);
            if (referrer != null) referrer.Points += (int)Math.Floor(50 * 1.0m);          // 4
        }
        customer.Tier = customer.Points > 1000 ? "Gold" : customer.Points > 200 ? "Silver" : "Bronze"; // 5
        db.Customers.Add(customer);
        await db.SaveChangesAsync(ct);
        return customer.Id;
    }

    public async Task RecordPurchase(Guid customerId, decimal amount, CancellationToken ct)
    {
        var c = await db.Customers.FindAsync([customerId], ct);
        c!.Points += (int)Math.Round(amount / 10);                                        // 4 again, different rounding
        c.Tier = c.Points > 1000 ? "Gold" : c.Points > 200 ? "Silver" : "Bronze";         // 5 again
        await db.SaveChangesAsync(ct);
    }

    public async Task<string> ExportCsv(CancellationToken ct) =>                           // 6
        string.Join('\n', await db.Customers.Select(c => $"{c.Name},{c.Email},{c.Dob}").ToListAsync(ct));

    public void LegacyImport(string path) { /* unused since 2023 */ }                    // 7
    // ...invoice email methods
}

Findings, ranked by severity

# Severity Smell / issue Comment I'd leave Now or debt
3 Correctness Hidden side effect / temporal coupling: email before save Blocking: "If SaveChangesAsync fails, the customer gets a welcome email for an account that doesn't exist. Could we send after the save, or better, raise a CustomerSignedUp event handled via the outbox?" Now
1, 6 Privacy / security PII in logs; unmasked PII export with no authorisation Blocking: "Email and DOB are personal information under the Privacy Act; can we log the customer ID only? For the export, it needs an admin policy and should drop DOB unless there's a stated purpose." Now
2 Diagnostics / wrong behaviour Generic Exception, weak validation "This becomes a 500; a ValidationProblem (400) gives the caller something to fix." Now if PR touches it
4 Wrong data Duplicated code, already diverged (floor vs round) "Points rounding differs between sign-up and purchase. Worth a LoyaltyPolicy so there's one rule; happy to pair on it." Now if touched, else high-priority debt
5 Design Duplicated code + feature envy + primitive obsession (string tier) "Tier logic reads only Customer's data; consider customer.RecalculateTier() returning an enum." Suggest / debt
— Design God class (sign-up, loyalty, invoice emails, export), long method "Not for this PR: I'll log a ticket to split loyalty and export out." Debt
— Design Primitive obsession: string email, Guid customerId Non-blocking suggestion Debt
7 Dispensable Dead code "Safe to delete? No references and no calls in telemetry for [N] months." Now (cheap)

The rewrite (the parts this PR should fix)

public async Task<CustomerId> SignUp(SignUpRequest request, CancellationToken ct)
{
    var customer = Customer.Create(request.Name, request.Email, request.DateOfBirth);
    if (request.ReferralCode is { } code)
        await loyalty.CreditReferrerAsync(code, ct);

    db.Customers.Add(customer);
    customer.Raise(new CustomerSignedUp(customer.Id));   // welcome email sent by a handler after commit (outbox)
    await db.SaveChangesAsync(ct);

    logger.LogInformation("Customer {CustomerId} signed up", customer.Id.Value); // no PII
    return customer.Id;
}

How I'd close the review

  • Summary comment: "Thanks, the referral flow reads well. Two blockers (email before save; PII in logs and export), one strong suggestion (single loyalty rule), and I've raised [ticket ids] for splitting loyalty/export out of this class and for typed IDs. Happy to pair on the outbox bit."
  • Labels: blocking: / suggestion: / nit: prefixes so the author knows what gates the merge.
  • Debt tickets each say what it costs ("every loyalty change touches 2 methods that already disagree") and the trigger to fix it ("before the loyalty tiers project in Q[N]").
  • Stop repeating comments: add a logging analyser or a custom rule that flags known PII property names in log templates, and an architecture test that exports require an admin policy.

Production example

A review like this typically merges within a day with two blocking fixes, instead of stalling for a week on a rewrite request, and the debt tickets carry enough context (cost, trigger) that a product owner can schedule them.

🔍 What the interviewer is checking

Checks whether the candidate can find smells and real risks in realistic code, rank them by severity, and run a kind, pragmatic review that separates blockers from debt.

Green flags

  • Finds the email-before-save and PII issues first, not naming
  • Names smells precisely and links them to refactorings
  • Has a clear rule for fix-now versus debt
  • Writes kind, specific, labelled comments and debt tickets with cost and trigger
  • Mentions automating recurring findings

Red flags

  • Only lists style issues or misses the correctness and privacy risks
  • Demands a rewrite in the same PR
  • Harsh or vague review tone

📚 Learn in depth

1. Severity ordering

Reviews have a fixed budget of attention, the author's and yours. Order findings by consequence:

1. Crash, data loss, security, privacy   -> blocks merge
2. Wrong data / wrong behaviour           -> blocks if introduced or touched
3. Diagnostics (logging, errors)          -> usually fix now, cheap
4. Design smells                          -> suggest or log as debt
5. Style / nits                           -> analyser, not a human

2. Naming smells precisely

Precise names make comments short and impersonal, and they point to known refactorings:

Smell Signal in this code Refactoring
God class 4 responsibilities, 4 reasons to change Extract class: LoyaltyService, CustomerExport
Long method SignUp validates, emails, credits, tiers, saves Extract method; move to entity
Hidden side effect / temporal coupling Email before save Domain event + outbox
Duplicated code Points and tier logic twice, diverged Extract LoyaltyPolicy
Feature envy Tier from Customer.Points in service Move method to Customer
Primitive obsession string email, string Tier, Guid IDs Value objects, enum, typed IDs
Dead code LegacyImport Delete (check telemetry first)

3. Fix now versus debt: a decision rule

Is it a correctness, security or privacy risk?        -> block
Did this PR introduce it or make it worse?            -> fix now
Is it in lines this PR already changes and cheap?     -> suggest, author decides
Pre-existing, structural, not touched?                -> debt ticket with cost + trigger

This follows the "boy scout rule" in moderation: leave touched code a bit better, but don't expand a PR's scope into a refactoring the author didn't plan and the reviewer of that PR can't verify.

4. Writing a debt ticket that gets done

A useful debt entry has: the smell, the location, the cost in delivery terms (time, defects, risk), the trigger that should prompt fixing it (an upcoming feature), and a rough size. "Refactor CustomerAccountService" is ignored; "Loyalty rules duplicated in 2 places with different rounding, caused [ticket]; fix before loyalty tiers work; ~2 days" gets scheduled.

5. Privacy in reviews (Australia)

The Privacy Act 1988 and APP 11 require reasonable steps to protect personal information; logs and ad-hoc exports are common leak paths and can feed a Notifiable Data Breach. Reviewers should treat names, emails, dates of birth, addresses and identifiers in logs or files as a security finding. .NET 8+ also has Microsoft.Extensions.Compliance.Redaction for classifying and redacting data in logs.

6. Tone

Conventional Comments (suggestion:, issue (blocking):, nit:), questions instead of commands where you are unsure, and one sentence of why per comment. Praise something specific. Offer to pair on the hard part.

Try it yourself

  1. Take a recent PR you reviewed and re-rank your comments by the severity ladder above.
  2. Write a debt ticket for one smell in your codebase with cost, trigger and size.
  3. Search your logs for email-shaped strings (@) to find PII leaks.
  4. Try Microsoft.Extensions.Compliance.Redaction with a [PersonalData]-style classification on a log property.

💻 Code

The loyalty duplication and tier envy fixed with one policy and a method on Customer; this is the strong suggestion from the review.

// Before: two diverged copies inside the service
c!.Points += (int)Math.Round(amount / 10);
c.Tier = c.Points > 1000 ? "Gold" : c.Points > 200 ? "Silver" : "Bronze";
// After: one rule, behaviour on the data, enum instead of string
namespace Shop.Loyalty;

public enum LoyaltyTier { Bronze, Silver, Gold }

public static class LoyaltyPolicy
{
    public const int ReferralBonus = 50;

    // One rounding rule, agreed with the product owner
    public static int PointsFor(decimal purchaseAmount) =>
        (int)Math.Floor(purchaseAmount / 10m);

    public static LoyaltyTier TierFor(int points) => points switch
    {
        > 1000 => LoyaltyTier.Gold,
        > 200 => LoyaltyTier.Silver,
        _ => LoyaltyTier.Bronze
    };
}

public sealed class Customer
{
    public int Points { get; private set; }
    public LoyaltyTier Tier { get; private set; }

    public void AddPoints(int points)
    {
        ArgumentOutOfRangeException.ThrowIfNegative(points);
        Points += points;
        Tier = LoyaltyPolicy.TierFor(Points); // invariant kept in one place
    }
}
// Unit tests pin the rule both old paths now share
public class LoyaltyPolicyTests
{
    [Theory]
    [InlineData(9.99, 0)]
    [InlineData(10.00, 1)]
    [InlineData(19.99, 1)]
    public void PointsFor_rounds_down(decimal amount, int expected) =>
        Assert.Equal(expected, LoyaltyPolicy.PointsFor(amount));

    [Theory]
    [InlineData(200, LoyaltyTier.Bronze)]
    [InlineData(201, LoyaltyTier.Silver)]
    [InlineData(1001, LoyaltyTier.Gold)]
    public void TierFor_uses_strict_thresholds(int points, LoyaltyTier expected) =>
        Assert.Equal(expected, LoyaltyPolicy.TierFor(points));
}

⚠ Common mistakes

  • Mistake: Reviewing in file order and leading with naming nits. Why it is wrong: The author fixes trivia and the data-loss bug gets less attention. Instead: Order comments by severity and put blockers first.
  • Mistake: Asking for every smell to be fixed in this PR. Why it is wrong: The PR balloons, conflicts grow and the risky change becomes unreviewable. Instead: Fix what the PR introduces or touches; log the rest as debt with cost and trigger.
  • Mistake: Accepting a fix without a test. Why it is wrong: The email-before-save bug and the diverged rounding will come back in the next change. Instead: Ask for a unit test that pins the loyalty rule (e.g. PointsFor(19.99m) == 1) and an integration test (WebApplicationFactory with a fake IEmailSender) proving no email is sent when SaveChangesAsync throws.
  • Mistake: Logging debt as "refactor X". Why it is wrong: Nobody can prioritise it. Instead: State the cost, the trigger and a size.
  • Mistake: Treating PII in logs as a style issue. Why it is wrong: It is a privacy risk under the Privacy Act 1988 (APP 11) and can contribute to a notifiable data breach. Instead: Block, and add redaction (Microsoft.Extensions.Compliance.Redaction) or an analyser so it doesn't recur.
  • Mistake: Vague or personal comments ("this is a mess"). Why it is wrong: They hurt and give the author nothing to act on. Instead: Name the smell, explain the risk in one sentence, suggest a fix, label blocking or not.
  • Mistake: Not labelling blocking versus optional. Why it is wrong: Authors either fix everything or argue about everything. Instead: Use prefixes such as blocking:, suggestion:, nit:.
  • Mistake: Repeating the same comment in every review. Why it is wrong: Humans are an expensive linter. Instead: Turn recurring findings into analysers, .editorconfig rules or architecture tests.

🏛 Senior insight: trade-offs

The senior skill here is triage, not detection. Anyone can list smells; a senior reviewer decides which ones gate the merge, writes them so the author can act in one pass, and turns the rest into debt that a product owner can actually schedule. The review is also a teaching moment: naming the smell once, with a link, grows the team's vocabulary more than fixing it for them.

I measure review health, not just code: time to first review, review rounds per PR, and how many debt tickets created from reviews get done. If debt tickets never get picked up, I take the top ones to planning with their cost attached.

Option When it fits Cost When not to
Block the PR Correctness, security, privacy, or the PR makes a smell worse Delay for author Pre-existing design smells not touched
Suggest in this PR Cheap fix in lines already changed Minutes Fix would double the PR's scope
Debt ticket Structural smell, real cost, no time now Writing a good ticket Trivial fixes: just do them
Analyser / architecture test Same comment keeps recurring Setup once One-off issue

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says they would log smells as technical debt Why: Checks how they prioritise debt and get time to pay it down
    How to answer

    Technical debt is the future cost of a shortcut, and the interest is the extra effort or risk it adds every time we work near it. I make it visible in a debt register with each item's impact, how often we pay its interest (change frequency, incidents, delays) and a rough cost to fix. I prioritise by interest, not by how ugly the code is: debt in a hotspot that slows every feature beats a messy module nobody touches. I get time by explaining it in business terms (lead time, incident risk, cost), by reserving a steady share of capacity, and by pairing debt fixes with features that touch the same area.

  2. When: Candidate flags the email sent before saving Why: Checks their understanding of hidden side effects and command-query separation
    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.

  3. When: Candidate names several smells quickly Why: Checks they can explain what a smell is and how it differs from a bug
    How to answer

    A code smell is a surface symptom in code that suggests a deeper design problem. Unlike a bug, the code still behaves correctly; the smell makes it harder and riskier to change. The term comes from Kent Beck and Martin Fowler's Refactoring, where each smell is paired with the refactorings that remove it.

    The ones I see most in .NET business code:

    • Long method and god class (a 2,000-line OrderService)
    • Primitive obsession: raw Guid customerId, Guid orderId that are easy to swap, where modern C# makes a strongly typed readonly record struct OrderId(Guid Value) cheap; and long parameter lists
    • Feature envy, duplicated code and switch statements on a type code

    The trade-off: a smell is a reason to look, not an order to refactor. I fix the ones in code we change often and leave stable, rarely touched code alone.

🛠 Real-world problems: how you handle them

Review of a sign-up change that sent welcome emails for failed sign-ups
Situation
A customer accounts service for [a retail loyalty programme], [~3,000] sign-ups a day. A PR added referral codes to `CustomerAccountService.SignUp`, a 250-line class also handling loyalty, invoice emails and CSV export.
Signals
During review: the welcome email was sent before `SaveChangesAsync`; logs included email and date of birth; points calculation differed between two methods. In production history: support tickets from people who got a welcome email but couldn't log in, and [a finance query] about loyalty point mismatches.
Investigation
Read the PR in severity order; checked Application Insights for failed `SaveChangesAsync` calls on sign-up ([~0.4%] from unique-constraint violations on email) which matched the support tickets; searched Log Analytics for email-shaped strings and found PII in [90] days of logs; compared the two points calculations and their rounding.
Resolution
Left two blocking comments (move the email to an outbox-backed `CustomerSignedUp` handler; remove PII from logs and restrict the export to an admin policy) and one strong suggestion (single `LoyaltyPolicy`), which the author took in the same PR. Raised [three] debt tickets with cost and trigger: split loyalty and export out of the class, typed IDs, remove `LegacyImport`. Worked with the platform team to purge PII from existing logs under our privacy procedure.
Prevention
Added `Microsoft.Extensions.Compliance.Redaction` with data classifications on customer properties; a custom analyser warns on known PII property names in log templates; the PR template gained a 'personal information' checkbox; the team adopted `blocking:` / `suggestion:` / `nit:` comment prefixes.

How to tell it (STAR)

**S:** At [company] I reviewed a PR adding referral codes to a 250-line customer service that also handled loyalty, emails and exports. **T:** I wanted to get the feature merged safely without turning it into a rewrite. **A:** I reviewed in severity order. Two blockers: the welcome email was sent before the save, which matched support tickets about phantom accounts, and email and date of birth were in our logs. I suggested one loyalty policy because the rounding had already diverged, and logged three debt tickets with cost and trigger for the structural smells. I paired with the author on the outbox change. **R:** The PR merged [the next day], phantom-account tickets went to [zero], PII was removed from logs and blocked by an analyser, and [two] of the three debt tickets were done within [two sprints].

↩ Usually asked after

More in Code Smells

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me