Walks through Extract Method and Extract Class on an order service, how Roslyn-based IDE refactorings handle parameters, return values and references, and the cases (out parameters, async, reflection, captured state) where they still change behaviour.
Extract Method takes a block that does one identifiable thing and gives it a name: variables the block reads become parameters, a variable it writes and the caller uses becomes the return value. Extract Class moves a cohesive group of fields and methods (for example, all the GST logic) into a new type that the original class delegates to.
IDE refactorings (Visual Studio's Extract Method, Rider's Extract Method and Extract Class) work on Roslyn's semantic model, so they find every real reference and compute parameters correctly. They can still surprise you: several written variables produce out parameters, async and lambdas need care, and reflection, JSON names or DI-by-convention are invisible to them.
The trade-off: extraction helps when the new name says more than the code; extracting single lines just adds jumps.
"Extract method is the refactoring I use most. I select a block that does one thing I can name, say the GST calculation inside
PlaceOrder, and the IDE turns it into a method. Whatever local variables the block reads become parameters, and the one it assigns that the caller uses afterwards becomes the return value. If the IDE wants to create two or threeoutparameters, that's feedback: the block is doing more than one thing, so I pick a smaller block or return a record.Extract class is the next step up. Once I see that a group of methods and fields always go together, like the GST rate, the rounding rule and three calculation methods, and they don't touch the rest of the class, I move them into a
GstCalculator, and the original class holds an instance and delegates. In Rider that's one refactoring; in Visual Studio I usually do it as create class, then Move members or cut and paste with the compiler guiding me, because Visual Studio has Extract Interface and Extract Base Class but not a full Extract Class.The reason I use the IDE rather than doing it by hand is that it works on the semantic model. It knows which
totalis which, updates every call site, and won't break overload resolution. But it can't see reflection, string-based bindings, or JSON property names, and it's careful but not perfect withasyncblocks, earlyreturns inside the selection and variables captured by lambdas. So after each extraction I build, run the tests and commit.The mistake I see is extracting for the sake of it: ten two-line methods with names like
DoStep2. The test is whether the name tells me more than the code did."
| In the selected block a variable is⦠| It becomes⦠|
|---|---|
| Read but declared outside | A parameter |
| Declared inside and not used after | A local in the new method |
| Assigned inside and used after | The return value |
| Two or more assigned and used after | out/ref parameters (or you return a tuple/record) |
this members used |
Stays an instance method; static only if none are used |
Contains await |
New method is async Task<T>, call site awaited |
| Refactoring | Visual Studio | Rider |
|---|---|---|
| Extract Method | Ctrl+R, Ctrl+M | Ctrl+Alt+M |
| Rename | Ctrl+R, Ctrl+R | Ctrl+R, R |
| Extract Interface | Ctrl+R, Ctrl+I | Refactor This β Extract Interface |
| Extract Class | Not built in (use Move/Extract Base Class or ReSharper) | Refactor This β Extract Class |
| Move type to file | Quick Actions (Ctrl+.) | Refactor This β Move to Folder/File |
| Signal | Extract |
|---|---|
| A comment explains what the next 10 lines do | Method, named after the comment |
| The same 3 fields are used by 4 methods and nothing else | Class |
| A method needs 5 parameters from its parent class | Maybe a class (the data and behaviour belong together) |
| One-line expression already reads clearly | Nothing |
In an order service, PlaceOrder was 180 lines. Four Extract Method steps (validate, price, persist, notify) and one Extract Class (GstCalculator, with 9 unit tests of its own) took about 90 minutes across 5 commits. Code review time on the next GST change dropped from an hour of reading to a 10-minute review of one 40-line class.
Checks that the candidate can perform the two most common refactorings mechanically and safely, and knows the limits of IDE automation.
Green flags
out parameters as a design signalRed flags
Extract Method is a data flow problem. Roslyn's SemanticModel.AnalyzeDataFlow(...) reports, for a selected region, which variables flow in (DataFlowsIn), which flow out (DataFlowsOut), which are written inside, and which are captured by lambdas. The IDE refactoring uses that analysis to build the signature.
before region region after region
var subtotal = ... -> reads subtotal ->
var rate = 0.10m -> reads rate ->
writes gst -> uses gst => gst is the return value
writes temp -> (unused) => temp stays local
If more than one variable flows out, the IDE must use out parameters or, in newer versions, offer a tuple. Either way, it's telling you the block has two outputs, which usually means two responsibilities.
Roslyn's AnalyzeControlFlow checks whether the region has a single entry and how it exits. A selection that contains a return from the outer method, a break out of an enclosing loop, or yield return can't always be extracted cleanly: the IDE either refuses or generates a flag/bool return the caller has to check. That's a sign to pick a different boundary.
If the selection contains await, the new method is async Task<T> and the call site gets await. If the original method was async void (an event handler), make sure the extracted method returns Task, not void. Variables captured by a lambda inside the selection keep their closure semantics, but if you extract the lambda's body separately the capture can change from per-iteration to shared, which matters in loops.
Extract Class is a sequence of smaller refactorings:
1. create class GstCalculator
2. move field _gstRate (Move Field)
3. move methods using it (Move Method; old methods delegate)
4. inline the delegating methods at call sites (Inline Method)
5. inject GstCalculator via constructor / DI
Each step compiles and passes tests on its own. Rider automates steps 1-4. In Visual Studio you can do them by hand with the compiler errors as a to-do list.
Reflection (GetMethod("CalculateGst")), nameof in other repositories, JSON property names, EF Core conventions, Razor asp-action strings, Moq Setup on methods you just made non-virtual or moved, and InternalsVisibleTo test projects in other solutions. Tests and a solution-wide build are the safety net.
out parameters, undo, and pick a smaller block.await and confirm the IDE makes the method async Task<T>.AnalyzeDataFlow on a block and print DataFlowsIn/DataFlowsOut.Before: pricing, GST and email text tangled in one method.
namespace Orders;
public sealed record OrderLine(string Sku, int Quantity, decimal UnitPrice, bool GstFree);
public sealed record Order(Guid Id, string CustomerEmail, IReadOnlyList<OrderLine> Lines);
public interface IOrderRepository { Task SaveAsync(Order order, decimal total, CancellationToken ct); }
public interface IEmailSender { Task SendAsync(string to, string body, CancellationToken ct); }
public sealed class OrderServiceBefore(IOrderRepository orders, IEmailSender email)
{
public async Task<decimal> PlaceOrderAsync(Order order, CancellationToken ct)
{
// work out subtotal and GST
decimal subtotal = 0, gst = 0;
foreach (var line in order.Lines)
{
var amount = line.Quantity * line.UnitPrice;
subtotal += amount;
if (!line.GstFree)
gst += Math.Round(amount * 0.10m, 2, MidpointRounding.AwayFromZero);
}
var total = subtotal + gst;
await orders.SaveAsync(order, total, ct);
// build the email
var body = $"Thanks for your order {order.Id}. Subtotal {subtotal:C}, GST {gst:C}, total {total:C}.";
await email.SendAsync(order.CustomerEmail, body, ct);
return total;
}
}
After: Extract Method turned the commented blocks into named steps, and Extract Class moved the GST rule into its own tested type.
namespace Orders;
public sealed record OrderTotals(decimal Subtotal, decimal Gst)
{
public decimal Total => Subtotal + Gst;
}
// Extracted class: the only place that knows the GST rate and rounding rule.
public sealed class GstCalculator
{
private const decimal Rate = 0.10m;
public OrderTotals Calculate(IEnumerable<OrderLine> lines)
{
decimal subtotal = 0, gst = 0;
foreach (var line in lines)
{
var amount = line.Quantity * line.UnitPrice;
subtotal += amount;
if (!line.GstFree)
gst += Math.Round(amount * Rate, 2, MidpointRounding.AwayFromZero);
}
return new OrderTotals(subtotal, gst);
}
}
public sealed class OrderService(IOrderRepository orders, IEmailSender email, GstCalculator gst)
{
public async Task<decimal> PlaceOrderAsync(Order order, CancellationToken ct)
{
var totals = gst.Calculate(order.Lines); // was the first commented block
await orders.SaveAsync(order, totals.Total, ct);
await email.SendAsync(order.CustomerEmail, ConfirmationBody(order, totals), ct);
return totals.Total;
}
// Extract Method: static because it uses no instance state.
private static string ConfirmationBody(Order order, OrderTotals t) =>
$"Thanks for your order {order.Id}. Subtotal {t.Subtotal:C}, GST {t.Gst:C}, total {t.Total:C}.";
}
// Program.cs: register the extracted class
builder.Services.AddSingleton<GstCalculator>(); // stateless, safe as singleton
builder.Services.AddScoped<OrderService>();
out parameters. Why it is wrong: it hides a block with several responsibilities behind an awkward signature. Instead: choose a smaller block, or return a record that names the results.Step1, Helper). Why it is wrong: readers jump around without learning anything. Instead: only extract when the name says more than the code.async void handler into another async void. Why it is wrong: exceptions crash the process and can't be awaited. Instead: extracted methods return Task.public "to test it". Why it is wrong: it widens the API for test convenience. Instead: test through the public method, or extract a class whose public surface is meant to be tested.Extract Method is cheap and reversible (Inline Method undoes it), so try boundaries freely and keep the ones whose names read like the business process. Extract Class is a design decision: it creates a new dependency and a new place for logic to live, so do it when you've found a real concept (GST, shipping rules, a confirmation email) that has its own reasons to change and deserves its own tests.
The IDE is a speed tool, not a correctness proof. On teams I'd rather see five 3-line commits of automated refactorings than one hand-crafted 300-line diff.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Extract Method | A named step hidden in a long method | Seconds; trivially reversible | Expression already clear; would need several out parameters |
| Extract local function | Helper only meaningful inside one method | Seconds | Needed elsewhere or should be tested alone |
| Extract Class | Cohesive data + behaviour with its own reason to change | New type, DI registration, tests | Only to shorten a file; no real concept |
| Leave it | Code is stable and rarely read | Nothing | You're about to change it |
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.
Cohesion is how strongly the parts of a module belong together. A highly cohesive class has methods that work on the same data towards one purpose, so a change to that concept happens in one place. Low cohesion shows up as Utils or Manager classes with unrelated methods, fields that only one or two methods use, and classes that change for many different reasons. I improve it by grouping code around domain concepts and features, moving methods to the data they use, and splitting classes whose fields form separate clusters.
How to tell it (STAR)
**S:** Our order service calculated GST in three places inside one 180-line method, and the last two GST changes had both caused production bugs. **T:** I had to add GST-free handling for [product line] without another incident. **A:** I first wrote characterisation tests over synthetic orders. Then, with Rider's automated refactorings, I extracted validate, price, persist and notify methods, and moved the GST logic into a `GstCalculator` class, one commit per step with tests green. The actual feature became a small change to one class. **R:** The feature PR was [n] lines and approved in [time]; we had zero GST incidents in the following [period], and the next GST-related change took [days] instead of the usual [days].
Last updated 23 Nov 2026.