Zum Inhalt springen

Refactoring large C# classes step by step

An OrderService with 514 lines hands over its shipping. Tests pin the behaviour, analysis and code graph show what changed at the cut.

by CodeCharter
  • csharp
  • refactoring
  • architecture

A developer is due to add partial deliveries to an online shop next quarter. Shipping lives in OrderService, a class with 514 lines of code, 46 methods and seven constructor parameters, and no tests. The line and method counts come from purpose-written threshold rules, because the CLI does not output metric values. The article on technical debt argued why this class is next, and specifically the part the feature touches. This article shows the refactoring itself in three commits: tests, helpers, extraction. The solution and code are constructed; the outputs come from real runs with CodeCharter v1.7.0 and the codeguard/csharp-all profile v1.3.0.

The analysis reports 15 findings for the class, including these five on size and structure:

$ codecharter analyze Shop.slnx --no-color
Rules: 248 from codeguard/csharp-all@1.3.0
…
  --- Warning (4) ---
  WARN   [Architecture] High response for class
        Shop.Ordering.OrderService
        .\src\Shop\Ordering\OrderService.cs:8
  WARN   [Design] Constructor has too many parameters
        Shop.Ordering.OrderService
        .\src\Shop\Ordering\OrderService.cs:8
  WARN   [Complexity] High weighted methods per class
        Shop.Ordering.OrderService
        .\src\Shop\Ordering\OrderService.cs:8
…
  INFO   [Design] Class too large
        Shop.Ordering.OrderService
        .\src\Shop\Ordering\OrderService.cs:8
  INFO   [Design] Too many public methods
        Shop.Ordering.OrderService
        .\src\Shop\Ordering\OrderService.cs:8
…
────
  21 violations (1 error, 4 warnings, 16 infos)
  Analyzed 35 types, 103 methods in 5,9s

class-too-large fires above 500 lines of code, too-many-public-methods above 20 public methods. The god-class rule requires more than 1000 lines and more than 30 methods and reports nothing here. None of the messages says where the class can be split.

Seams in the code

graph neighborhood lists all method signatures of OrderService and the types it uses or that use it:

$ codecharter graph neighborhood OrderService
Focus: Shop.Ordering.OrderService (class)  .\src\Shop\Ordering\OrderService.cs:8
  public OrderService(IOrderRepository orders, ICustomerRepository customers, IStockService stock, IPaymentGateway payments, IMailSender mail, IClock clock, PriceCalculator prices)
  …
  public void MarkPacked(Guid orderId)
  public void Ship(Guid orderId, string trackingNumber)
  public void MarkDelivered(Guid orderId)
  public static string? TrackingUrl(Order order)
  public IReadOnlyList<Order> OverdueShipments(TimeSpan allowedTime)
  …
Used by (2):
  Shop.Api.OrderEndpoint (class)  .\src\Shop\Api\OrderEndpoint.cs:6  distance 1  [Uses]
  Shop.Backoffice.StaleOrderJob (class)  .\src\Shop\Backoffice\StaleOrderJob.cs:5  distance 1  [Uses]
…

The graph works at type level. It shows that OrderService uses eleven types, but not which method needs which dependency. CodeCharter does compute a cohesion metric (Henderson-Sellers LCOM), but outputs it nowhere, and no rule in the profile reads it. Determined through custom threshold rules, it is at least 0.99 for OrderService. Parameters of a primary constructor do not count as fields. Here the value therefore only measures accesses to five constants and a dictionary. With the same seven dependencies written as explicit fields, it drops to 0.92 (probed in steps of 0.01). Nothing about the structure changes.

The developer therefore finds the seams in the code. For each public method she counts which constructor parameters it uses, directly or through private helpers. A small script over the method bodies does this in one pass; the IDE's reference search gives the same result method by method. A cross means at least one method in the group uses the dependency:

Method group orders customers stock payments mail clock prices
Ordering (PlaceOrder, Reorder) x x x x x x
Payment (Pay) x x x x
Shipping (MarkPacked, Ship, MarkDelivered, TrackingUrl, OverdueShipments) x x x x
Cancellation (Cancel, CancelStaleDrafts, CanCancel) x x x x x x
Returns (ReturnLines) x x x x x x
Line changes (ChangeQuantity, AddLine, CorrectUnitPrice) x x x x
Mails (SendPaymentReminders, ResendConfirmation) x x x x x
Queries and export (six methods) x

No group owns a dependency on its own. 20 of the 23 public methods use orders; only the static TrackingUrl and CanCancel and ExportCsv do without. Whoever extracts a group therefore hands it dependencies without getting rid of them in OrderService. The groups also share private helpers. How the developer deals with them later decides whether the new class gets free of the old one.

Shipping as the first responsibility

Shipping comes first because the feature touches it. The group needs four of the seven dependencies and none of stock, payments and prices. Nobody in the solution calls its five methods: OrderEndpoint uses PlaceOrder and Cancel, StaleOrderJob uses CancelStaleDrafts. Nothing changes from the outside, and the compiler confirms this on the first build.

The queries and export group would be the cleaner cut, since it needs only orders. But no change to it is planned, and refactoring it would not make partial deliveries any easier. The table also shows that the OrderService constructor keeps seven parameters after the refactoring, because orders, customers, mail and clock are needed elsewhere too. The too-many-ctor-params finding stays.

Characterisation tests

Martin Fowler defines refactoring as a change to the internal structure that makes code easier to understand and cheaper to modify. It does so without changing observable behaviour. A characterisation test pins this behaviour as it is today, not as a specification would demand it. For shipping, what is observable is the status an order receives and when it is saved. The mail with its text and the exceptions with their messages are observable too.

The developer writes ten test cases against the unchanged OrderService and replaces the repository, customer store, mail sender and clock with small fakes. An eleventh test builds the DI container. Two tests show the principle:

[Fact]
public void Ship_sends_exactly_this_mail()
{
    AddOrder(OrderStatus.Packed);

    CreateSut().Ship(OrderId, "1Z 999/A");

    var mail = Assert.Single(_mail.Sent);
    Assert.Equal("ada@example.com", mail.To);
    Assert.Equal("Order 3F2A9C1E is on its way", mail.Subject);
    Assert.Equal(
        "Hello Ada,\r\n" +
        "\r\n" +
        "your order 3F2A9C1E left our warehouse on 2026-11-10.\r\n" +
        "Track it here: https://tracking.example.com/1Z%20999%2FA\r\n" +
        "\r\n" +
        "   2 x BOOK-42                   24.00 EUR\r\n" +
        "\r\n" +
        "Your shop team\r\n",
        mail.Body);
}

[Fact]
public void Ship_sends_no_mail_when_saving_fails()
{
    AddOrder(OrderStatus.Packed);
    _orders.IsUnavailable = true;

    Assert.Throws<IOException>(() => CreateSut().Ship(OrderId, "1Z999"));

    Assert.Empty(_mail.Sent);
}

The first test pins the whole mail text, including the URL encoding of the tracking number and the width of the line item. It also pins the line ending. AppendLine writes Environment.NewLine, which is \r\n on Windows. The test is therefore bound to the platform and would fail on a Linux runner. In the case it ran on Windows only. Teams that test on several platforms build the expected value from Environment.NewLine.

The second test pins the order: save first, then mail. The remaining eight check, among other things, status and save count, the trimmed tracking number, the messages for a wrong status and an unknown order, and the list of overdue shipments.

All eleven tests were green on the first run. Whether they really pin the behaviour only a counter-check shows. The developer introduces three defects into OrderService and reverts them afterwards:

Introduced defect Failing test
Send the mail before saving Ship_sends_no_mail_when_saving_fails
Date in the mail text as dd.MM.yyyy Ship_sends_exactly_this_mail
Trim() on the tracking number removed Ship_sets_status_trimmed_tracking_number_and_time_then_saves_once

Each defect makes exactly one test fail. The tests go to main as a commit of their own, before a single line of production code changes.

Shared helpers

Shipping shares five private helpers with the rest of the class. Load and LoadCustomer are one-liners that ShipmentService gets its own copies of. ShortId appears in 25 places across the class, in messages, mail subjects, mail bodies and the summary. EnsureTransition checks the allowed status changes and, apart from shipping, is only used by Pay. AppendLines formats the line items for the shipping and the confirmation mail.

These three helpers work only on Order and OrderLine, so the developer moves them there. That is the second commit, and OrderService keeps all its methods afterwards. After the move, the diff analysis against main reports four findings on the changed lines:

$ codecharter analyze Shop.slnx --git-ref main..HEAD --no-color
Rules: 248 from codeguard/csharp-all@1.3.0
Note: 10 finding(s) in diff-touched files fall outside the changed lines (e.g. class- or namespace-level findings) and were NOT gated. Re-run with --diff-context to report them.
  --- Info (4) ---
  INFO   [Style] Magic number literal
        8
        .\src\Shop\Domain\Order.cs:18
  INFO   [Style] Magic number literal
        10
        .\src\Shop\Domain\OrderLine.cs:15
  INFO   [Style] Magic number literal
        20
        .\src\Shop\Domain\OrderLine.cs:15
  INFO   [Style] Magic number literal
        4
        .\src\Shop\Domain\OrderLine.cs:15
────
  4 violations (4 infos)
  Analyzed 35 types, 102 methods in 3,3s

The numbers 8, 4, 20 and 10 used to sit in OrderService.cs. CodeCharter does not detect moves; to the gate they are new. A baseline written on main reports the same four. Without --fail-on, the run exits with 1 even on info findings. The developer names the numbers and adds them to the same commit. Order then looks like this:

internal sealed class Order
{
    private const int ShortIdLength = 8;
    …
    public string ShortId => Id.ToString("N")[..ShortIdLength].ToUpperInvariant();

    public void EnsureCanMoveTo(OrderStatus next)
    {
        if (!AllowedNext(Status).Contains(next))
            throw new InvalidOperationException($"Order {ShortId} cannot change from {Status} to {next}.");
    }
    …
}

EnsureCanMoveTo only checks and does not set the status. Pay sets it only after a successful payment, and that order is meant to stay. The line item moves along as OrderLine.ToMailLine(); its widths are now called QuantityWidth, SkuWidth and TotalWidth. The diff analysis then reports 0 findings, and the build and the eleven tests stay green.

Extraction behind an interface

In the third commit the five shipping methods and the shipping mail move into ShipmentService. The class gets only the four dependencies the table shows for shipping:

internal sealed class ShipmentService(
    IOrderRepository orders,
    ICustomerRepository customers,
    IMailSender mail,
    IClock clock) : IShipmentService
{
    …
    /// <inheritdoc/>
    public void Ship(Guid orderId, string trackingNumber)
    {
        if (string.IsNullOrWhiteSpace(trackingNumber))
            throw new ArgumentException("A tracking number is required.", nameof(trackingNumber));

        var order = Load(orderId);
        order.EnsureCanMoveTo(OrderStatus.Shipped);
        order.Status = OrderStatus.Shipped;
        order.TrackingNumber = trackingNumber.Trim();
        order.ShippedAt = clock.Now;
        orders.Save(order);

        SendShippingMail(order, LoadCustomer(order));
    }
    …
}

IShipmentService contains MarkPacked, Ship, MarkDelivered and OverdueShipments. OrderService.cs loses 69 lines in this commit. The composition root AddShop registers the new service with the same lifetime as OrderService:

services.AddScoped<OrderService>();
services.AddScoped<IShipmentService, ShipmentService>();

A test builds the container with ValidateOnBuild and ValidateScopes and resolves IShipmentService. Scope validation catches a singleton holding on to a scoped service, an error that Microsoft's DI guidelines describe as a "captive dependency". If the registration is missing, the test fails with "No service for type 'Shop.Shipping.IShipmentService' has been registered."

In the characterisation tests, only the object they build changes:

-    private OrderService CreateSut() => new(
-        _orders, new InMemoryCustomers(_customer), new UnusedStock(), new UnusedPayments(),
-        _mail, _clock, new PriceCalculator());
+    private ShipmentService CreateSut() => new(
+        _orders, new InMemoryCustomers(_customer), _mail, _clock);

Add the using line and the call to ShipmentService.TrackingUrl. No expectation changes, and all eleven tests are green. To check that they still bite in the new place, the developer repeats the first defect: sending the mail before saving makes Ship_sends_no_mail_when_saving_fails fail again.

Checks after the refactoring

The full analysis then reports 15 findings, down from 21. For OrderService the count drops from 15 to 9. Which ones disappeared depends on the rule thresholds. The values in the table come from purpose-written threshold rules, one rule of the form "value greater than or equal to x" per metric, because the CLI does not output them:

OrderService, since main before after Rule threshold Finding
Lines of code (class-too-large) 514 434 above 500 gone
Public methods (too-many-public-methods) 23 18 above 20 gone
Constructor parameters (too-many-ctor-params) 7 7 above 4 stays
WMC (weighted-methods-per-class) 132 110 above 50 stays
RFC (response-for-class) 88 72 above 50 stays

class-too-large disappears because the class slips 66 lines below the threshold. Ordering, payment, cancellation, returns, line changes, dunning and export are all still in it. The three warnings that remain describe that more accurately than the lower line count. The other four findings that went away are the named numbers. ShipmentService and IShipmentService have no findings.

graph diff compares the graph with main and shows what changed in the relationships:

$ codecharter graph diff --base main
…
Nodes: 35 -> 37 (+2/-0). Edges: 109 -> 121 (+18/-6/~7).
…
Changed edges (7):
  ~ Shop.Domain.Order -Uses-> Shop.Domain.OrderStatus (weight 1 -> 4)
  ~ Shop.Ordering.OrderService -Uses-> Shop.Domain.Customer (weight 12 -> 10)
  ~ Shop.Ordering.OrderService -Calls-> Shop.Domain.IMailSender (weight 6 -> 5)
  ~ Shop.Ordering.OrderService -Calls-> Shop.Domain.IOrderRepository (weight 23 -> 18)
  ~ Shop.Ordering.OrderService -Uses-> Shop.Domain.Order (weight 23 -> 17)
  ~ Shop.Ordering.OrderService -Uses-> Shop.Domain.OrderLine (weight 5 -> 4)
  ~ Shop.Ordering.OrderService -Uses-> Shop.Domain.OrderStatus (weight 4 -> 1)
Coupling changes (14):
  ShipmentService                                               fanIn   0 -> 1    fanOut   0 -> 8
  …
  OrderService                                                  fanIn   3 -> 2    fanOut   11 -> 11
  …

Apart from its own interface, the new edges of ShipmentService lead to IOrderRepository, ICustomerRepository, IMailSender, IClock, Order, OrderLine and Customer. None leads to OrderService. OrderService still uses eleven types, just less often: calls to IOrderRepository drop from 23 to 18. The status rule now lives in Order, visible in the weight rising from 1 to 4. The first call rebuilt the main side in 19.9 s, the second came from the cache in 2.6 s.

The graph also shows a gap. The registration AddScoped<IShipmentService, ShipmentService>() creates no edge; ShopServices has not a single outgoing relationship in the graph. graph impact IShipmentService therefore names only ShipmentService and the test, not the composition root. The article on dependencies in the code graph describes the same gap. Anyone reworking an interface checks the registrations through the container test.

In the pull request, the diff analysis stays green and only states the number of existing findings:

$ codecharter analyze Shop.slnx --git-ref main..HEAD --no-color
Rules: 248 from codeguard/csharp-all@1.3.0
Note: 9 finding(s) in diff-touched files fall outside the changed lines (e.g. class- or namespace-level findings) and were NOT gated. Re-run with --diff-context to report them.
No violations found.
  0 violations
  Analyzed 37 types, 108 methods in 3,8s

With --diff-context, the same call reports these nine findings in OrderService.cs and exits with 1. All nine were already on main, among them, as an error, the empty catch block in CapturePayment, which Pay calls. Without --fail-on, any one of these nine findings turns the gate red. If the gate runs with this option, the team decides in the refactoring PR which of the nine old findings it fixes along the way or moves into a baseline. These runs show v1.7.0. In versions after v1.7.1, --git-ref without --diff-context no longer only counts these findings: those at or above --fail-on (every one when --fail-on is not given) fail the run and are named on stderr by severity and rule; --diff-context still reports all of them, and --no-diff-context-gate restores the count-only behaviour (analyze documentation). The call without --fail-on above then also exits with 1, so the decision about the nine old findings is due in either case.

The case itself shows that a single refactoring barely moves the overall measures: OrderService still uses eleven types and needs seven constructor parameters. Szőke and colleagues reached a similar picture in six industrial systems written mostly in Java. The 315 refactoring commits they examined fixed 1,273 coding issues, an oversized class only five times. A single commit hardly changed the measured maintainability, sometimes it made it worse. Over the whole refactoring period it rose in five of the six systems. Suggestions and measurement came from the same toolkit, as the authors themselves point out. The study therefore does not answer whether Extract Class pays off.

IDE and tests without an analysis tool

The obvious alternative does without the analysis tool. The Visual Studio documentation lists Extract Method, Extract Interface and Extract Base Class for C#. It names no refactoring that moves instance members into a new class. The Roslyn source code, on which Visual Studio's C# refactorings are built, additionally contains the action "Move static members to another type". It moves static members into a new or existing type and updates the references. That would cover the three static helpers, but not the shipping methods, because they use the constructor parameters.

Rider has Extract Class. It creates a reference field in the original, optionally with delegating wrappers, and warns when remaining members use a moved private member. Neither IDE was run for the case.

The shortest route leaves the helpers where they are and only makes them visible. In the case, EnsureTransition, ShortId and AppendLines become internal static, and ShipmentService calls them as OrderService.ShortId(order). The build and all eleven tests are green, just as on the other branch. The code graph shows the difference:

$ codecharter graph impact OrderService
Traversal includes reversed implements edges (interface  implementation).
Dependents by distance (2 level(s)):
  Distance 1 (3):
    Shop.Api.OrderEndpoint (class)  .\src\Shop\Api\OrderEndpoint.cs:6
    Shop.Backoffice.StaleOrderJob (class)  .\src\Shop\Backoffice\StaleOrderJob.cs:5
    Shop.Shipping.ShipmentService (class)  .\src\Shop\Shipping\ShipmentService.cs:8
…

On the branch with moved helpers, the same command reports two direct dependents. Here ShipmentService calls into OrderService six times. Every change to the status rule or the mail format remains a change to OrderService that affects shipping. A reviewer sees the six calls in the diff as well. The tool turns that into one line that can be repeated in every PR.

If the method groups share no private helpers, the helper question disappears altogether. In the case that almost holds for queries and export, which use at most orders and of which only Summarize touches Load and ShortId. There, Extract Class and tests do the same job as the route with analysis.

IDE and tests are also enough when no analysis gate runs in the PR, the class has few dependents and the developer checks the cut in the diff herself. For behavioural equivalence they do the same job in the case as the route with analysis, because both rely on the same eleven tests. The analysis shows which findings disappeared at a threshold and which remained. It shows whether the new class still depends on the old one. It also shows which existing findings a gate with --diff-context reports in the refactoring PR.

Partial deliveries now start from a class with four dependencies and eleven tests. ShipPartially belongs in ShipmentService. The developer again picks the next group to leave OrderService by the next feature and by the dependency table.