Defines a code smell versus a bug, groups the classic smells (bloaters, couplers, change preventers, object-orientation abusers, dispensables) and names the ones most common in .NET business code.
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.
"A code smell is a symptom you can see on the surface of the code that hints at a deeper design problem. The important word is hints: smelly code usually works, passes its tests and ships. What it does is make the next change slower and riskier. That is the difference from a bug: a bug is wrong behaviour today, a smell is a likely source of wrong behaviour and slow delivery tomorrow. The vocabulary comes from Kent Beck and Martin Fowler's Refactoring, and the useful thing about it is that every smell has a name and a matching set of refactorings, so in a review I can say 'this is feature envy, move the method to
Invoice' instead of 'this feels wrong'.In .NET business code the usual suspects are very consistent. Long methods, often a controller action or a MediatR handler that does validation, pricing, persistence and email in one place. God classes: an
OrderServiceorCustomerManagerthat every feature touches. Primitive obsession: IDs, money and email addresses passed around asGuid,decimalandstring, so nothing stops you passing a customer ID where an order ID belongs. Long parameter lists, duplicated logic across handlers, andswitchstatements on an enum repeated in several methods.The mistake I see is treating smells as rules: refactoring every long method in the codebase, or failing a PR because a class has 301 lines. A smell is a prompt to look. If the code is stable and rarely changed, the smell costs almost nothing. If it is in the file that every sprint touches, it is worth fixing, one small test-backed refactoring at a time."
| Term | What it is | Code works? | Example |
|---|---|---|---|
| Bug | Wrong behaviour | No | GST rounded per line instead of per invoice |
| Code smell | Symptom of a design problem | Yes | PlaceOrder is 300 lines long |
| Technical debt | The cost of the design problem over time | Yes | Every pricing change takes 3 days and breaks something |
| Group | Idea | Smells |
|---|---|---|
| Bloaters | Code grew too big to hold in your head | Long method, large (god) class, long parameter list, primitive obsession, data clumps |
| Object-orientation abusers | OO features used badly or not at all | Switch on type code, refused bequest, temporary field |
| Change preventers | One change forces many edits | Divergent change, shotgun surgery, parallel inheritance hierarchies |
| Dispensables | Code that adds nothing | Dead code, speculative generality, duplicated code, lazy class, comments that explain bad code |
| Couplers | Classes know too much about each other | Feature envy, inappropriate intimacy, message chains, middle man |
| Smell | Typical .NET form |
|---|---|
| Long method | A 200-line controller action or MediatR handler |
| God class | OrderService with 40 public methods and 12 constructor dependencies |
| Primitive obsession | Guid customerId, Guid orderId; string email; decimal amount with no currency |
| Feature envy | InvoiceService.CalculateTotal(invoice) reading ten properties of Invoice |
| Message chain | order.Customer.Address.Region.TaxRate |
| Switch on type code | switch (invoice.Kind) repeated in five methods |
| Speculative generality | IRepository<T> over EF Core with one implementation and no second use |
In a typical order system, the OrderService that every feature touches accumulates long methods and primitive parameters first. A team that tracks change frequency will often find that 5% of files receive 40% or more of the commits; those files are where fixing smells pays back, for example cutting a pricing change from three days to half a day.
Checks that the candidate knows what a smell is, can name common ones with .NET examples, and applies judgement rather than rules.
Green flags
Guid IDs, switch on enum)Red flags
Kent Beck coined "code smell" while helping Martin Fowler write Refactoring: Improving the Design of Existing Code (1999; second edition 2018, examples in JavaScript). The book's chapter 3, "Bad Smells in Code", lists the smells and points each one at refactorings from the catalogue. The metaphor is deliberate: a smell tells you something might be off, and you have to look to find out.
Most smells hurt in one of three ways:
Comprehension -> you cannot hold the code in your head (long method, god class)
Change cost -> one change needs edits in many places (shotgun surgery, duplication)
Safety -> the type system cannot protect you (primitive obsession, temporary field)
Each of these turns into lead time and defects. A 300-line method is hard to test, so it gets fewer tests, so changes to it break things, so people avoid changing it and add new branches instead. Smells feed themselves.
| Smell | First refactorings to reach for |
|---|---|
| Long method | Extract method, replace temp with query, decompose conditional |
| God class | Extract class, move method, split by responsibility |
| Long parameter list | Introduce parameter object, preserve whole object |
| Primitive obsession | Replace primitive with value object, strongly typed IDs |
| Feature envy | Move method to the class whose data it uses |
| Switch on type code | Replace conditional with polymorphism or a strategy map |
| Duplicated code | Extract method or class, but only for real (same reason to change) duplication |
| Shotgun surgery | Move related behaviour into one module |
The .NET SDK ships Roslyn code-quality rules that flag some smells, though several are off by default:
SonarQube adds cognitive complexity (S3776), duplicated blocks and method length rules. Visual Studio's Analyze > Calculate Code Metrics gives maintainability index, cyclomatic complexity and class coupling per type. These find candidates; a person still decides.
switch that maps 40 error codes to messages is long but easy to read.The question is always: does this make the next likely change harder?
.editorconfig at warning and see what they flag.git log --format=format: --name-only | sort | uniq -c | sort -rn | head -20 to find the most-changed files, then look for smells in them.A small order handler with four common smells, then the same logic with them removed.
// Before: works, but smells
namespace Shop.Orders.Before;
public class OrderService(ShopDbContext db)
{
// Smell: long parameter list + primitive obsession (two Guids are easy to swap)
public async Task<decimal> PlaceOrder(Guid customerId, Guid productId, int qty,
string couponCode, string country, bool isMember, CancellationToken ct)
{
var product = await db.Products.FindAsync([productId], ct)
?? throw new InvalidOperationException("Product not found");
// Smell: switch on a type code, repeated elsewhere in the class
decimal discount = couponCode switch
{
"TENOFF" => 0.10m,
"STAFF" => 0.25m,
_ => 0m
};
if (isMember) discount += 0.05m;
// Smell: feature envy - this belongs with the order line
var total = product.Price * qty * (1 - discount);
if (country == "AU") total *= 1.10m; // magic number: GST
db.Orders.Add(new Order { CustomerId = customerId, ProductId = productId, Quantity = qty, Total = total });
await db.SaveChangesAsync(ct);
return total;
}
}
// After: same behaviour, smells named and removed
namespace Shop.Orders.After;
public readonly record struct CustomerId(Guid Value);
public readonly record struct ProductId(Guid Value);
// Parameter object replaces the long list
public sealed record PlaceOrderRequest(CustomerId Customer, ProductId Product, int Quantity,
string? CouponCode, string Country, bool IsMember);
public static class Gst
{
public const decimal Rate = 0.10m; // named, one place
}
public sealed record OrderLine(decimal UnitPrice, int Quantity)
{
// Behaviour moved to the data it uses
public decimal Total(decimal discount, string country)
{
var net = UnitPrice * Quantity * (1 - discount);
return country == "AU" ? net * (1 + Gst.Rate) : net;
}
}
switch. Instead: Ask whether the smell makes the next likely change harder.switch; failing builds on raw metric thresholds teaches people to game them. Instead: Use tools to find candidates, then apply context: how often the code changes and what breaks when it does.record with 15 primitive properties is still primitive obsession and a data clump. Instead: Use the new features as the tools for the refactoring, not as a substitute for it.OrderLine".Juniors learn the list; seniors learn the economics. A smell matters in proportion to how often the code changes and how much breaks when it does. The best predictor of where smells hurt is change frequency multiplied by complexity (Adam Tornhill's "hotspots"), which you can get from git history in minutes, or from tools such as CodeScene. I then tie it to business impact: lead time for changes in that area (from Azure DevOps or GitHub PR data), defects linked to those files in the bug tracker, and incidents seen in Application Insights. Fixing smells in hotspots is the highest-return refactoring a team can do; fixing them in cold code is mostly risk.
The other senior move is using smell names as shared vocabulary. "Primitive obsession" in a review comment is faster and less personal than a paragraph about how the parameters are confusing.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Fix the smell now | Hotspot code you are already changing | Small PR, needs tests | Code you are not otherwise touching this sprint |
| Log it as debt | Real cost but no time now | A ticket and a sentence of context | Trivial smells that a two-minute fix would remove |
| Leave it | Stable, rarely changed code | None | Code that blocks a planned feature |
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.
Combine change frequency from git history with complexity. Count commits per file (git log --name-only), and measure complexity with code metrics or SonarQube cognitive complexity. Files that are both frequently changed and complex are hotspots; they are where smells slow delivery and cause defects. Tools such as CodeScene automate this, but a spreadsheet of the top 20 files works. Cross-check with the bug tracker and add other debt signals such as duplicated blocks and architecture rule violations. Then weigh it against the roadmap: cold code that a planned feature will soon touch moves up the list, while cold code nobody plans to change can wait in the debt register rather than be ignored for ever.
Last updated 23 Nov 2026.