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.
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.
"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."
| 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 |
| 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 |
Refactor: extract GstCalculator (no behaviour change).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.
Checks that the candidate knows refactoring means behaviour-preserving change and treats tests as a precondition, not an afterthought.
Green flags
Red flags
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.
| 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.
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
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.
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.
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.
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.
git log --oneline on a recent refactoring of yours: could a reviewer tell refactor commits from behaviour commits?Verify.Xunit package) to snapshot the output of a report generator, then refactor it.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)"
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 |
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.
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.
Last updated 23 Nov 2026.