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

📚 Interview question

What is refactoring, and what isn't it? Why do you need tests before you start, and how do you keep a refactoring safe while you work?

Defines refactoring as behaviour-preserving structural change, separates it from rewrites, fixes and features, and explains why tests (or characterisation tests) and small committed steps make it safe.

Junior Theory Beginner characterisation-tests code-quality csharp ide-refactorings refactoring unit-testing

🎯 Key points

  • Refactoring = change structure without changing observable behaviour: outputs, exceptions, persisted state, messages and calls to other systems, public contract
  • Not a rewrite, not a bug fix, not a feature: do those in separate commits
  • Tests first: they are the cheap proof behaviour is unchanged
  • No tests? Write characterisation tests that pin today's behaviour, bugs included
  • Across system boundaries, use integration and contract tests (DB rows written, events published, HTTP payloads)
  • Small named steps (rename, extract method, move): run tests, commit after each
  • Prefer IDE automated refactorings (Visual Studio, Rider) over hand edits
  • Refactor where you are about to change code (preparatory refactoring); it is how you pay down technical debt cheaply

⏱ 30-second answer

Refactoring is changing the internal structure of code without changing its observable behaviour, in small, reversible steps, so it becomes easier to understand and cheaper to change. It is not a rewrite, a bug fix or a new feature: if outputs, side effects or the public contract change, it is no longer a refactoring, and it belongs in a separate commit.

You need tests first because they are the only cheap proof that behaviour didn't change. Where there are none, write characterisation tests that pin down what the code does today, bugs included. Then work in tiny steps: one named refactoring (rename, extract method, move), run the tests, commit.

The trade-off: refactoring spends time now to buy speed later, so do it where you are about to change code, not across the whole codebase.

🗣 Full answer (senior)

How I would answer this in an interview

"Refactoring is changing how code is structured without changing what it does. Martin Fowler's definition is the one I use: a change to the internal structure of software to make it easier to understand and cheaper to modify, without changing its observable behaviour. Observable means the return values, the side effects like database writes and emails, the exceptions callers rely on, and the public API. If any of those change, I'm not refactoring any more, I'm changing behaviour, and that goes in its own commit with its own tests.

So refactoring isn't a rewrite, it isn't fixing a bug, and it isn't adding a feature. In practice I alternate hats: I refactor to make the change easy, commit, then make the easy change. Tests are what make that safe. Before I touch anything I run the tests that cover the code. If there aren't any, I write characterisation tests first: I call the code with realistic inputs and assert whatever it returns today, even if it looks wrong, because my job in that moment is to keep it the same, not to judge it.

Then I go in very small steps: one named refactoring, like rename or extract method, run the tests, commit. I lean on the IDE's automated refactorings in Visual Studio or Rider, because they update every call site and understand C# semantics, where find-and-replace does not.

The mistake I see is the 'refactoring' PR that also changes the GST rounding and adds a field. When a bug turns up, nobody can tell which part caused it, and the reviewer can't verify anything. Keep structure changes and behaviour changes apart, and the review becomes trivial."


Refactoring versus the things it gets confused with

Change Behaviour changes? Example How to review it
Refactoring No Extract CalculateGst from PlaceOrder Tests unchanged and green; diff is mechanical
Bug fix Yes, on purpose GST rounded per line instead of per invoice New failing test first, then fix
Feature Yes Add surcharge for card payments New tests, product sign-off
Rewrite Unknown until proven New pricing engine from scratch Parallel run, comparison, staged rollout
Reformatting No dotnet format Separate commit, ideally automated

Why tests come first

Situation What to do before refactoring
Good unit tests cover the code Run them; make sure they're green and fast
Tests exist but are thin Add tests for the paths you're about to touch
No tests at all Characterisation tests (assert current output, e.g. with Verify snapshots)
Code can't be tested as it is Use safe IDE-only refactorings to create a seam first, then add tests

The safe loop

  1. Tests green.
  2. One small refactoring (preferably automated by the IDE).
  3. Build and run tests.
  4. Commit with a message like Refactor: extract GstCalculator (no behaviour change).
  5. Repeat. If tests go red, revert the last step rather than debugging forward.

Production example

In an invoicing service with a 400-line GenerateInvoice method, adding characterisation tests over 30 real-shaped (synthetic) invoices took half a day. The refactoring that followed went out as 12 small PRs over two weeks, each reviewed in under 15 minutes, with zero invoice differences in production, and the next feature on that code took 2 days instead of the estimated 6.

🔍 What the interviewer is checking

Checks that the candidate knows refactoring means behaviour-preserving change and treats tests as a precondition, not an afterthought.

Green flags

  • Defines observable behaviour (outputs, side effects, contract)
  • Mentions characterisation tests for untested code
  • Small steps with tests and commits between them
  • Keeps behaviour changes in separate commits
  • Knows IDE refactorings are semantic but blind to reflection and strings

Red flags

  • Uses "refactoring" to mean any change or a rewrite
  • "I'd just be careful" without tests
  • Plans one big refactoring branch

📚 Learn in depth

1. Behaviour is what callers can observe

A refactoring is defined against an observer. For a private method, the observer is the rest of the class. For a public API, it is every caller, including ones you can't see: other services, serialised payloads, database columns, message consumers.

          what changes            what must stay the same
  +--------------------------+  +----------------------------------+
  | method boundaries        |  | return values                    |
  | class boundaries         |  | exceptions callers rely on       |
  | names (internal)         |  | persisted state: rows, columns   |
  | data structures (private)|  | messages/events published        |
  |                          |  | calls to other services (+order) |
  |                          |  | public API and wire format       |
  +--------------------------+  +----------------------------------+

Things the compiler can't see are where "pure refactorings" break behaviour: renaming a property that System.Text.Json serialises, an EF Core property mapped by convention to a column, a class name used in a DI registration by reflection, or a string in a Razor view. Before renaming anything public, check for those.

Protecting behaviour at system boundaries

Boundary Test that pins it
Database writes Integration test against real SQL Server (Testcontainers) asserting rows
HTTP API responses WebApplicationFactory tests, or snapshot the JSON with Verify
Calls to other services Contract tests (e.g. Pact) or WireMock.Net asserting requests
Published events Assert on an in-memory or test-container broker, including the payload shape

The more external interactions the code has, the more of the safety net has to live at these boundaries, because unit tests with mocks only prove the code calls the mock the same way.

2. The two hats

Kent Beck's idea: at any moment you wear one hat. With the refactoring hat you change structure and tests stay as they are. With the feature hat you add behaviour and add tests. Switching hats is fine; wearing both at once is how bugs hide in diffs.

  refactor (tests unchanged) -> commit -> feature (new test, red -> green) -> commit

3. Characterisation tests

Michael Feathers' term for tests that describe what the code does, not what it should do. You write a test, run it, look at the actual output, and paste that into the assertion. Snapshot libraries such as Verify make this fast for large outputs. If the output reveals a bug, note it and fix it later, as a separate behaviour change.

4. Why small steps are faster

The cost of finding a mistake grows with the size of the change since the last green test run. With 2-minute steps, a red test points to the last 2 minutes of work and you revert. With a 2-day refactoring, a red test starts an investigation. Committing after each green step also gives reviewers a readable story.

5. Automated refactorings

Roslyn-based IDE refactorings (Rename, Extract Method, Change Signature, Move Type to File, Introduce Parameter) work on the semantic model, not text, so they find every real reference and skip unrelated identifiers with the same name. They are still blind to reflection, strings and other repositories, which is why you still run tests.

6. Refactoring and technical debt

Refactoring is the main tool for paying down technical debt, and small preparatory refactorings are the cheapest way to pay it: the interest (slower changes, more bugs) is only paid on code you change, so that's where repayment has the best return.

Try it yourself

  1. Take a method in your codebase with no tests. Write three characterisation tests that assert its current output, then do one Extract Method and rerun them.
  2. Rename a public DTO property used in a JSON API and watch which tests catch the wire-format change (if none do, add a serialisation test).
  3. Use git log --oneline on a recent refactoring of yours: could a reviewer tell refactor commits from behaviour commits?
  4. Try Verify (Verify.Xunit package) to snapshot the output of a report generator, then refactor it.

💻 Code

A characterisation test that pins today's behaviour of a legacy calculator before refactoring it, including an odd rounding the business may rely on.

namespace Billing.Tests;

using Billing;
using Xunit;

public sealed class InvoiceCalculatorCharacterisationTests
{
    // Inputs taken from realistic (synthetic) invoices. Expected values were
    // copied from what the current code returns, not from a spec.
    [Theory]
    [InlineData(100.00, false, 110.00)]
    [InlineData(33.33, false, 36.66)]   // rounds GST to 3.33, total 36.66 today
    [InlineData(100.00, true, 100.00)]  // GST-free item
    public void Total_matches_current_behaviour(decimal subtotal, bool gstFree, decimal expected)
    {
        var calculator = new LegacyInvoiceCalculator();

        var total = calculator.Total(subtotal, gstFree);

        Assert.Equal(expected, total);
    }
}
namespace Billing;

// The code under test, before refactoring. The test above lets us restructure it
// (extract GstCalculator, rename variables) and prove nothing changed.
public sealed class LegacyInvoiceCalculator
{
    public decimal Total(decimal subtotal, bool gstFree)
    {
        decimal t = subtotal;
        if (!gstFree)
        {
            var g = Math.Round(subtotal * 0.10m, 2, MidpointRounding.AwayFromZero);
            t = t + g;
        }
        return t;
    }
}
# The loop: one refactoring, test, commit
dotnet test --filter "FullyQualifiedName~InvoiceCalculator"
git commit -am "Refactor: extract GST calculation (no behaviour change)"

⚠ Common mistakes

  • Mistake: Mixing a behaviour change into a refactoring PR. Why it is wrong: when something breaks, nobody can tell which change caused it, and reviewers can't verify the mechanical part. Instead: separate commits or PRs: refactor first, then change behaviour, and label refactoring PRs so reviewers check 'no behaviour change' rather than the logic.
  • Mistake: Refactoring code with no tests "carefully". Why it is wrong: care is not evidence; subtle changes (rounding, ordering, null handling) slip through. Instead: write characterisation tests first.
  • Mistake: Only checking return values. Why it is wrong: behaviour also includes what the code writes to the database, the events it publishes, the order of calls to other services and the HTTP payloads it sends; a refactor that changes the order of two writes or a JSON field name breaks other systems while unit tests stay green. Instead: cover those boundaries with integration tests (Testcontainers, WebApplicationFactory) and contract tests.
  • Mistake: "Fixing" a bug you notice while writing characterisation tests. Why it is wrong: callers may depend on the bug, and you've changed behaviour under a refactoring label. Instead: pin the current behaviour, log the bug, fix it separately with product agreement.
  • Mistake: Calling a rewrite a refactoring. Why it is wrong: it hides the risk; a rewrite needs comparison testing and a rollout plan. Instead: name it honestly and plan it as a rewrite.
  • Mistake: Big-bang refactoring branches that live for weeks. Why it is wrong: merge conflicts with feature work and a huge, unreviewable diff. Instead: small steps merged to main daily.
  • Mistake: Renaming public or widely used symbols with plain find-and-replace. Why it is wrong: text search hits unrelated identifiers with the same name and misses semantic references (overloads, interface implementations). It can be fine for a private local in one file, but it doesn't scale. Instead: use the IDE's Rename (Ctrl+R, Ctrl+R in Visual Studio, Ctrl+R, R in Rider), then search for string usages it can't see.
  • Mistake: Assuming a green build means behaviour is preserved. Why it is wrong: reflection, JSON names and EF conventions are invisible to the compiler. Instead: have serialisation and integration tests for public contracts.

🏛 Senior insight: trade-offs

Refactoring is an economic decision, not a hygiene ritual. The best time to refactor is just before a change to that code (preparatory refactoring): the payback is immediate and the tests you write serve the feature too. Refactoring stable code nobody touches has almost no return.

The senior skill is making refactoring invisible to the schedule: small steps folded into feature work, never a separate "refactoring sprint" that has to be justified.

Approach When it fits Cost When not to
Preparatory refactoring Before a feature in messy code Small, paid back immediately Code you won't touch again
Opportunistic (boy scout) Small cleanups while passing through Minutes When it bloats a feature PR
Planned refactoring A module blocking many features Days to weeks, needs a plan Without tests or a clear goal
Rewrite Design can't support requirements High, risky When refactoring can get there

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions characterisation tests or untested legacy code Why: Checks they can actually get hard-to-test code under test before refactoring it
    How to answer

    In Michael Feathers' terms, legacy code is code without tests, so the job is to make this change safe, not to reach a coverage number. First I write characterisation tests: run the code with a range of inputs and assert whatever it currently does, bugs included. For calculations, a golden master with Verify captures hundreds of input combinations in one snapshot. To get the code into a test harness I look for seams, places where behaviour can be swapped without editing that spot: virtual methods, a constructor I can parameterise, an interface I can extract. I make those refactorings small and mechanical, using IDE automated refactorings. New logic goes in a sprout method or class that is tested from the start. The trade-off: some ugly intermediate code (extra constructors, wrapper interfaces) in exchange for a safety net before the real change.

  2. When: Candidate talks about refactoring a whole module or system Why: Checks they can plan a large refactoring without stopping feature delivery
    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.

↩ Usually asked after

More in Refactoring

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me