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.
I'd read it for risk first, style last. Ranked:
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.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.
"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
SignUpand again inRecordPurchase, 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 oneLoyaltyPolicynow; 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,SignUpis a long method, emails and IDs are raw strings andGuids, the tier calculation enviesCustomer, and there's an unusedLegacyImportmethod. 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."
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
}
| # | 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) |
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;
}
blocking: / suggestion: / nit: prefixes so the author knows what gates the merge.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.
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
Red flags
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
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) |
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.
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.
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.
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.
@) to find PII leaks.Microsoft.Extensions.Compliance.Redaction with a [PersonalData]-style classification on a log property.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));
}
PointsFor(19.99m) == 1) and an integration test (WebApplicationFactory with a fake IEmailSender) proving no email is sent when SaveChangesAsync throws.Microsoft.Extensions.Compliance.Redaction) or an analyser so it doesn't recur.blocking:, suggestion:, nit:..editorconfig rules or architecture tests.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 |
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.
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.
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:
OrderService)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 listsThe 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.
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].
Last updated 23 Nov 2026.