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

📚 Interview question

What is a code smell? How is it different from a bug, and which smells do you most often find in real .NET codebases?

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.

Junior Theory Beginner code-quality code-smells csharp maintainability refactoring

🎯 Key points

  • A smell is a surface symptom that suggests a deeper design problem, not a defect: the code still works
  • Term from Kent Beck and Martin Fowler's Refactoring (1999, 2nd ed. 2018); each smell maps to named refactorings
  • Groups: bloaters, object-orientation abusers, change preventers, dispensables, couplers
  • Common in .NET: long method, god class/service, primitive obsession, long parameter list, feature envy, duplicated code
  • Modern C# makes fixes cheap: records and readonly record struct IDs for primitive obsession, switch expressions and pattern matching for conditionals
  • A smell is a prompt to look, not a rule: prioritise by change frequency and business impact
  • Fix with small, test-backed refactorings, not big rewrites
  • Tools find candidates (CA1502, CA1506, SonarQube cognitive complexity) but judgement decides

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 OrderService or CustomerManager that every feature touches. Primitive obsession: IDs, money and email addresses passed around as Guid, decimal and string, so nothing stops you passing a customer ID where an order ID belongs. Long parameter lists, duplicated logic across handlers, and switch statements 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."


Smell versus bug versus technical debt

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

The five classic groups

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

What they look like in a .NET codebase

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate knows what a smell is, can name common ones with .NET examples, and applies judgement rather than rules.

Green flags

  • Distinguishes smell from bug and from technical debt clearly
  • Names several smells with concrete .NET forms (fat handler, Guid IDs, switch on enum)
  • Links each smell to a refactoring
  • Says a smell is a prompt to look, and prioritises by change frequency

Red flags

  • Thinks a smell means the code is broken
  • Only gives vague answers ("messy code", "bad naming")
  • Wants to rewrite everything that smells

📚 Learn in depth

1. Where the word comes from

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.

2. Why smells slow you down

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.

3. Smell to refactoring map

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

4. Finding smells with tools

The .NET SDK ships Roslyn code-quality rules that flag some smells, though several are off by default:

  • CA1502 avoid excessive cyclomatic complexity
  • CA1506 avoid excessive class coupling
  • CA1505 avoid unmaintainable code (maintainability index)
  • IDE0051 / IDE0052 unused private members (dead code)

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.

5. Judgement: when a smell is fine

  • A 60-line switch that maps 40 error codes to messages is long but easy to read.
  • A DTO with only properties looks like a "data class" smell, but it is a DTO; that is its job.
  • Duplication across two bounded contexts is often correct: they change for different reasons.

The question is always: does this make the next likely change harder?

Try it yourself

  1. Run Analyze > Calculate Code Metrics on a solution you know and list the five types with the highest class coupling. Are they the ones you dread changing?
  2. Enable CA1502 and CA1506 in .editorconfig at warning and see what they flag.
  3. Run 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.
  4. Pick one long method and name every smell in it before you change anything.

💻 Code

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

⚠ Common mistakes

  • Mistake: Calling a smell a bug. Why it is wrong: Smelly code usually behaves correctly; calling it a bug confuses priorities and annoys product owners. Instead: Say what it costs: slower changes, harder testing, higher defect risk.
  • Mistake: Treating smells as hard rules ("no method over 20 lines"). Why it is wrong: Some long code is perfectly clear, such as a flat mapping switch. Instead: Ask whether the smell makes the next likely change harder.
  • Mistake: Refactoring smells in code nobody touches. Why it is wrong: All risk, no payback. Instead: Fix smells in files that change often (use git history to find them).
  • Mistake: Fixing a smell without tests. Why it is wrong: A refactoring that changes behaviour is a bug, not a refactoring. Instead: Add characterisation tests first, then refactor in small steps.
  • Mistake: Removing all duplication on sight. Why it is wrong: Coincidental similarity merged into one method creates the wrong abstraction. Instead: Merge only code that changes for the same reason.
  • Mistake: Treating analyser and metric warnings as the verdict. Why it is wrong: Tools miss feature envy and primitive obsession and flag harmless code such as a flat lookup 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.
  • Mistake: Thinking modern C# makes smells go away. Why it is wrong: Records, pattern matching and primary constructors make fixes cheaper, but a 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.
  • Mistake: Writing vague review comments ("this is messy"). Why it is wrong: The author cannot act on it. Instead: Name the smell and the refactoring: "feature envy, consider moving this to OrderLine".

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions long methods or large classes Why: Checks whether they know when splitting helps and when it hurts
    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 says to fix smells only where code changes often Why: Checks that they can measure hotspots instead of guessing
    How to answer

    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.

↩ Usually asked after

More in Code Smells

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me