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

πŸ“š Interview question

Show me extract method and extract class on a real C# example. How do the IDE refactorings in Visual Studio and Rider do it safely, and what can still go wrong?

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.

Intermediate Coding Intermediate code-quality csharp extract-class extract-method ide-refactorings refactoring

🎯 Key points

  • Extract Method: name a block by intent; locals read become parameters, locals written become return values
  • Several written locals produce out/ref parameters or a tuple: a sign the block does too much
  • Extract Class: move a cohesive group of fields and methods into a new type, then delegate
  • Visual Studio: Extract Method (Ctrl+R, Ctrl+M), Extract Interface, Extract Base Class; no built-in Extract Class (ReSharper adds one); Rider has Extract Class
  • IDE works on the Roslyn semantic model, so references update correctly, but reflection, strings and other repositories are invisible
  • IDE preserves mechanics, not intent: watch async/await, captured variables, early returns, exception flow and shared state
  • Don't extract when the name adds nothing, or when the new class has no cohesive reason to change
  • Run tests and commit after each extraction

⏱ 30-second answer

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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"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 three out parameters, 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 total is 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 with async blocks, early returns 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."


What the IDE works out for you

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

Shortcuts (default keymaps)

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

When to extract a method vs a class

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

Production example

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.

πŸ” What the interviewer is checking

Checks that the candidate can perform the two most common refactorings mechanically and safely, and knows the limits of IDE automation.

Green flags

  • Explains how parameters and return values are derived from data flow
  • Treats several out parameters as a design signal
  • Does Extract Class in small compiling steps and delegates
  • Names what the IDE can't see (reflection, JSON names, EF conventions)
  • Commits and tests after each step

Red flags

  • Extracts by cut and paste without tests
  • Creates meaningless helper names
  • Mixes logic changes into the extraction

πŸ“š Learn in depth

1. Data flow analysis is the core

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.

2. Control flow limits

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.

3. Async and captured state

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.

4. Extract Class mechanics

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.

5. What the IDE can't see

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.

Try it yourself

  1. Select a block that writes two variables used later and run Extract Method. Look at the generated out parameters, undo, and pick a smaller block.
  2. Extract a block containing await and confirm the IDE makes the method async Task<T>.
  3. Write a tiny Roslyn script calling AnalyzeDataFlow on a block and print DataFlowsIn/DataFlowsOut.
  4. In Rider, use Extract Class on a class with a cohesive set of fields; in Visual Studio, do the same by hand and compare the number of steps.

πŸ’» Code

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>();

⚠ Common mistakes

  • Mistake: Accepting an extracted method with two or three 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.
  • Mistake: Extracting tiny steps with meaningless names (Step1, Helper). Why it is wrong: readers jump around without learning anything. Instead: only extract when the name says more than the code.
  • Mistake: Doing Extract Class as one giant manual edit. Why it is wrong: nothing compiles for an hour and mistakes are hard to find. Instead: move one field or method at a time, compiling and testing in between.
  • Mistake: Extracting a class that splits a cohesive concept. Why it is wrong: the two classes now reach into each other's data (feature envy) and change together every time. Instead: extract only groups of fields and methods that are used together and change for the same reason.
  • Mistake: Trusting the IDE with reflection-based code. Why it is wrong: string lookups, JSON names and EF conventions aren't updated. Instead: search for string usages and keep serialisation and integration tests.
  • Mistake: Assuming the IDE preserves meaning, not just mechanics. Why it is wrong: it faithfully moves a lambda that captures a loop variable or a field that another thread mutates, but if the extracted method is later called from a new place, that captured or shared state is now touched from two paths; the IDE can't judge whether that is safe. Instead: check captured variables and shared state in the extracted code, and keep extracted methods free of hidden state where you can.
  • Mistake: Extracting a block from an 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.
  • Mistake: Making an extracted helper 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.
  • Mistake: Extracting and changing logic in the same commit ("while I was there"). Why it is wrong: the mechanical change can no longer be reviewed as mechanical. Instead: extract first, commit, then change.

πŸ› Senior insight: trade-offs

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

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate talks about making methods and classes small Why: Checks they know when splitting makes code harder to follow
    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 the extracted fields and methods 'belong together' Why: Checks they can name and measure cohesion as the reason for Extract Class
    How to answer

    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.

πŸ›  Real-world problems: how you handle them

Extracting GST logic before a rate-handling change
Situation
A [team size]-person team owned an order service where GST calculation lived in three places inside a 180-line `PlaceOrder` method. A change to handle GST-free items for [product line] was due in [timeframe].
Signals
Two previous GST changes had each caused a production bug; PRs touching `PlaceOrder` averaged [n] review comments and took over a day to approve.
Investigation
Read the method with Rider's code structure view, used Find Usages on the GST variables, checked code coverage (coverlet) on `PlaceOrder` (about 40%), and searched the solution for string references to the method.
Resolution
Added characterisation tests over synthetic orders, then did four Extract Method steps and one Extract Class (`GstCalculator`) as five separate commits, each with tests green. The GST-free change then touched only `GstCalculator` and its tests.
Prevention
Unit tests on `GstCalculator`, a team guideline that refactoring and behaviour changes go in separate commits, and an analyser rule flagging methods over [n] lines in PR checks.

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].

↩ Usually asked after

More in Refactoring

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me