Step-by-step refactor of a carrier switch into keyed shipping strategies: characterisation tests first, IShippingStrategy with a Carrier key, rates moved to options, a context that builds a dictionary once and fails fast on duplicates, DI registration, unit and registration tests, Open/Closed in practice, and when a switch is the better answer.
I'd refactor in safe steps. First, characterisation tests that pin today's prices for each carrier. Then extract IShippingStrategy with a Carrier key and Calculate(Parcel), and move each case into its own class with its own dependencies (rates from IOptions<T>, a remote-postcode lookup). The calculator becomes a context that receives IEnumerable<IShippingStrategy>, builds a dictionary once (a duplicate key throws at start-up) and returns a validation error for unknown carriers.
That satisfies Open/Closed: a new carrier is one class plus one registration line, and the existing carriers and the context don't change. Each strategy gets its own unit test, plus one test that builds the real container and checks every carrier is registered.
The trade-off is more types: for two or three stable one-line formulas, I'd keep the switch.
"I wouldn't start by writing classes, I'd start with a safety net. A pricing switch is exactly the kind of code where a refactor silently changes a number, so I'd write characterisation tests: a table of parcels, weights, postcodes and express flags for every carrier, asserting today's output, even where today's output looks odd. Once those pass, I extract an
IShippingStrategyinterface with aCarrierkey andCalculate(Parcel), and move each case into its own class:AusPostStrategy,StarTrackStrategy,DhlStrategy. Each class takes only what it needs: AusPost gets its rates throughIOptions<AusPostRates>, StarTrack also gets anIRemoteAreaLookupfor its remote-postcode surcharge. The characterisation tests should still pass unchanged.The old calculator becomes the context. It takes
IEnumerable<IShippingStrategy>, and in the constructor builds a case-insensitive dictionary byCarrier.ToDictionarythrows on a duplicate key, so if someone copies a class and forgets to change the key, the app fails at start-up instead of quoting the wrong carrier at checkout. Unknown carriers come back as aTryCalculatefalse and a 400, not a null reference. For Open/Closed, adding Sendle means one new class and oneAddSingleton<IShippingStrategy, SendleStrategy>()line. Nothing else is opened, and the code review only has to look at the new carrier.The mistake I see is replacing the switch with a factory that still switches on carrier to
newthe right class. The variant list is still edited in one central place, so you've added classes without the benefit. The other mistake is doing this for three carriers that haven't changed in years. I refactor to strategies when the switch keeps changing; the goal is that adding a variant stops being risky, not that the code looks patterned."
| Step | What changes | Safety check |
|---|---|---|
| 1. Characterisation tests | Nothing in production code | Tests pin current prices per carrier |
| 2. Extract interface and one class per case | Switch arms move into classes | Same tests pass |
3. Move rates to IOptions<T> |
Constants move to appsettings.json |
Same tests pass with the same values |
4. Context builds a dictionary from IEnumerable<T> |
Switch deleted | Duplicate keys throw at start-up |
| 5. Registration test | AddShipping() extension |
Asserts the expected carrier set |
| Concern | Switch | Strategies |
|---|---|---|
| Adding a carrier | Edit the shared method | Add a class and one registration |
| Per-carrier dependencies | All injected into one class | Each class takes only its own |
| Testing a carrier | Through the whole method | In isolation |
| Risk to other carriers | Shared variables, fall-through mistakes | None; separate classes |
| Discoverability | One file to read | Need to find the registration |
| Keep the switch | Refactor to strategies |
|---|---|
| 2β3 carriers, one-line formulas | 4+ carriers or growing |
| Rarely changes | Changed most sprints |
| No per-carrier dependencies | Carriers call APIs, need rates or lookups |
An e-commerce checkout added a carrier roughly every quarter, and each addition edited a 180-line switch. One release changed a shared surcharge variable and overcharged express parcels for an existing carrier by $7.50 for two days. After the refactor, the next three carriers each shipped as one class and one registration line, with no changes to existing pricing and no pricing incidents over the following year.
Checks whether the candidate can refactor safely (tests first), apply Strategy without leaving a hidden switch, and reason about Open/Closed and when the refactor isn't worth it.
Green flags
Red flags
A switch is not a smell. A switch is a problem when it is the place every change lands: it grows, cases share local variables, and a change for one carrier can break another. The goal of the refactor is to make each carrier's pricing an isolated unit that can be added, changed and tested without touching the others.
Michael Feathers' term: tests that describe what the code does, not what it should do. For a pricing function, a table-driven xUnit [Theory] with 20β40 rows per carrier (weights at boundaries, remote and metro postcodes, express on and off) captures behaviour cheaply. If a row looks wrong, record it as is and raise it separately; a refactor that also fixes bugs is impossible to review.
Checkout endpoint βββΆ ShippingCalculator (context)
_byCarrier: dictionary<string, IShippingStrategy>
TryCalculate(carrier, parcel)
β
Β«interfaceΒ» IShippingStrategy
Carrier : string
Calculate(Parcel) : decimal
β² β² β²
AusPostStrategy StarTrackStrategy DhlStrategy
(IOptions<Rates>) (IRemoteAreaLookup) (IOptions<Rates>)
ToDictionary throws ArgumentException on a duplicate key during construction. Register the calculator as a singleton and resolve it once at start-up (or use ValidateOnBuild) so the failure happens on deploy, not on the first checkout.TryCalculate returns false; the endpoint returns a 400 with a problem-details body.Carriers lets the UI list supported carriers from the same source of truth.The context and existing strategies are closed for modification. Program.cs (or an AddShipping() extension) still gets one new line, and that's fine: composition roots are meant to change. Assembly scanning with Scrutor (Scan(s => s.FromAssemblyOf<IShippingStrategy>().AddClasses(c => c.AssignableTo<IShippingStrategy>()).AsImplementedInterfaces())) removes even that line, at the cost of making registration implicit.
If carriers differ only in numbers (base, per-kg, express), you don't need a class per carrier: one RateTableStrategy configured from data per carrier is enough. Strategy earns its keep when carriers differ in logic: StarTrack's minimum charge and remote surcharge, DHL's dimensional weight, a carrier that calls a live quote API. Many real systems end up with both: a generic table-driven strategy plus a few special ones.
| Test | What it proves |
|---|---|
| Characterisation tests over the context | Refactor preserved prices |
| One unit test class per strategy | Each carrier's rules in isolation |
| Context with fake strategies | Selection, case-insensitivity, unknown and duplicate keys |
Registration test using the real AddShipping() |
Every expected carrier is wired up |
[Theory] over the original switch with at least 10 rows per carrier.Before: one method that every carrier edits, with rates hard-coded.
namespace Shipping;
public sealed record Parcel(decimal WeightKg, string Postcode, bool Express);
public enum Carrier { AusPost, StarTrack, Dhl }
public sealed class LegacyShippingCalculator
{
public decimal Calculate(Carrier carrier, Parcel parcel)
{
switch (carrier)
{
case Carrier.AusPost:
var cost = 9.95m + parcel.WeightKg * 1.20m;
if (parcel.Express) cost += 7.50m;
return cost;
case Carrier.StarTrack:
var remote = parcel.Postcode.StartsWith('0') ? 12m : 0m; // illustrative NT rule
return Math.Max(15m, parcel.WeightKg * 2.10m) + remote;
case Carrier.Dhl:
return 18m + parcel.WeightKg * 1.75m;
default:
throw new NotSupportedException($"Unknown carrier {carrier}");
}
}
}
After: one strategy per carrier, a context that selects by key, and DI registration.
namespace Shipping;
using System.Collections.Frozen;
using Microsoft.Extensions.Options;
public interface IShippingStrategy
{
string Carrier { get; } // the key used by the API and config
decimal Calculate(Parcel parcel);
}
public sealed record AusPostRates
{
public decimal Base { get; init; } = 9.95m;
public decimal PerKg { get; init; } = 1.20m;
public decimal ExpressSurcharge { get; init; } = 7.50m;
}
public sealed class AusPostStrategy(IOptions<AusPostRates> options) : IShippingStrategy
{
private readonly AusPostRates _rates = options.Value;
public string Carrier => "auspost";
public decimal Calculate(Parcel parcel) =>
_rates.Base + parcel.WeightKg * _rates.PerKg + (parcel.Express ? _rates.ExpressSurcharge : 0m);
}
public interface IRemoteAreaLookup { bool IsRemote(string postcode); }
public sealed class PostcodeRemoteAreaLookup : IRemoteAreaLookup
{
public bool IsRemote(string postcode) => postcode.StartsWith('0'); // illustrative; real data comes from a table
}
public sealed class StarTrackStrategy(IRemoteAreaLookup remoteAreas) : IShippingStrategy
{
public string Carrier => "startrack";
public decimal Calculate(Parcel parcel) =>
Math.Max(15m, parcel.WeightKg * 2.10m) + (remoteAreas.IsRemote(parcel.Postcode) ? 12m : 0m);
}
public sealed class DhlStrategy : IShippingStrategy
{
public string Carrier => "dhl";
public decimal Calculate(Parcel parcel) => 18m + parcel.WeightKg * 1.75m;
}
// The context: selection only. No carrier knowledge lives here any more.
public sealed class ShippingCalculator
{
private readonly FrozenDictionary<string, IShippingStrategy> _byCarrier;
public ShippingCalculator(IEnumerable<IShippingStrategy> strategies) =>
// ToDictionary throws ArgumentException on a duplicate key: a copy-paste mistake fails at start-up
_byCarrier = strategies
.ToDictionary(s => s.Carrier, StringComparer.OrdinalIgnoreCase)
.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
public IEnumerable<string> Carriers => _byCarrier.Keys;
public bool TryCalculate(string carrier, Parcel parcel, out decimal cost)
{
if (_byCarrier.TryGetValue(carrier, out var strategy))
{
cost = strategy.Calculate(parcel);
return true;
}
cost = 0m;
return false;
}
}
public static class ShippingServiceCollectionExtensions
{
// A new carrier = one new class + one line here. Nothing else changes.
public static IServiceCollection AddShipping(this IServiceCollection services, IConfiguration config)
{
services.Configure<AusPostRates>(config.GetSection("Shipping:AusPost"));
services.AddSingleton<IRemoteAreaLookup, PostcodeRemoteAreaLookup>();
services.AddSingleton<IShippingStrategy, AusPostStrategy>();
services.AddSingleton<IShippingStrategy, StarTrackStrategy>();
services.AddSingleton<IShippingStrategy, DhlStrategy>();
services.AddSingleton<ShippingCalculator>();
return services;
}
}
// Program.cs
builder.Services.AddShipping(builder.Configuration);
app.MapGet("/shipping/quote", (string carrier, decimal weightKg, string postcode, bool express,
ShippingCalculator calc, ILogger<ShippingCalculator> logger) =>
{
if (calc.TryCalculate(carrier, new Parcel(weightKg, postcode, express), out var cost))
return Results.Ok(new { carrier, cost });
// Log the rejected value: a spike usually means a client or config sent a new carrier name
logger.LogWarning("Quote requested for unsupported carrier {Carrier}", carrier);
return Results.Problem($"Unsupported carrier '{carrier}'.", statusCode: StatusCodes.Status400BadRequest);
});
// Tests (xUnit): context behaviour with fakes, a registration check against the real wiring, one carrier rule
namespace Shipping.Tests;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
public class ShippingCalculatorTests
{
private static readonly Parcel Sample = new(2m, "2000", Express: false);
private sealed record FakeStrategy(string Carrier, decimal Cost) : IShippingStrategy
{
public decimal Calculate(Parcel parcel) => Cost;
}
[Fact]
public void Selects_strategy_by_key_case_insensitively()
{
var calc = new ShippingCalculator([new FakeStrategy("auspost", 10m), new FakeStrategy("dhl", 20m)]);
Assert.True(calc.TryCalculate("DHL", Sample, out var cost));
Assert.Equal(20m, cost);
}
[Fact]
public void Unknown_carrier_returns_false() =>
Assert.False(new ShippingCalculator([new FakeStrategy("dhl", 20m)]).TryCalculate("sendle", Sample, out _));
[Fact]
public void Duplicate_keys_fail_fast() =>
Assert.Throws<ArgumentException>(() =>
new ShippingCalculator([new FakeStrategy("dhl", 1m), new FakeStrategy("DHL", 2m)]));
[Fact]
public void Every_expected_carrier_is_registered()
{
var config = new ConfigurationBuilder().Build();
using var sp = new ServiceCollection().AddShipping(config).BuildServiceProvider();
string[] carriers = [.. sp.GetRequiredService<ShippingCalculator>().Carriers.Order()];
Assert.Equal(new[] { "auspost", "dhl", "startrack" }, carriers);
}
// decimal can't appear in attributes, so cents are passed as long and converted
[Theory]
[InlineData(1, false, 1115L)]
[InlineData(1, true, 1865L)]
public void AusPost_prices(int kg, bool express, long expectedCents)
{
var strategy = new AusPostStrategy(Options.Create(new AusPostRates()));
Assert.Equal(expectedCents / 100m, strategy.Calculate(new Parcel(kg, "3000", express)));
}
}
new each strategy. Why it is wrong: The central edit point remains, so Open/Closed is not achieved. Instead: Register strategies in DI and let the context enumerate them.IEnumerable<IShippingStrategy> with FirstOrDefault per request. Why it is wrong: Duplicate keys are silently ignored and lookup is O(n). Instead: Build the dictionary once in the constructor so duplicates throw.NullReferenceException for an unknown carrier. Why it is wrong: Free shipping or a 500 error from a client typo. Instead: TryCalculate plus a 400 problem-details response.The value of this refactor is risk isolation, not elegance. I measure it by what the next change costs: files touched, reviewers needed, and whether existing carriers' tests even run differently. If adding a carrier still edits shared code, the refactor didn't finish.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Keep the switch expression | 2β3 stable variants | Edits one method per change | Variants grow or share risky state |
| Strategy per carrier + dictionary | Carriers differ in logic and change often | One class per carrier | Carriers differ only in numbers |
| Table-driven single strategy | Carriers differ only in rates | Config schema and validation | Logic differs per carrier |
| Keyed services | Carrier fixed per consumer | Keys in registration | Carrier comes from request data |
I also separate two improvements that often get bundled: moving rates to configuration and introducing strategies. Each is valuable on its own, and shipping them separately keeps both reviewable.
This is a Strategy (IPaymentGateway) chosen by a factory. There are three DI-friendly ways to do it:
AddKeyedScoped<IPaymentGateway, StripeGateway>("stripe"), then inject with [FromKeyedServices("stripe")]. This only works when the key is known at compile time.IEnumerable<IPaymentGateway> resolver: each gateway exposes a Provider key, and a resolver builds a FrozenDictionary from them. There's no container access, but every gateway is constructed.IPaymentGatewayResolver.Resolve(provider) calls GetRequiredKeyedService inside the composition root. It builds only the gateway you need.To avoid a service locator, business code depends on a narrow typed resolver, never on IServiceProvider. Map unknown keys to a domain error, and validate the configured keys at startup.
The Open/Closed Principle says modules should be open for extension but closed for modification: you add new behaviour by adding code, not by editing tested code. In C# this usually means a strategy interface with one implementation per variant, registered in DI, so adding a new payment method is a new class rather than another case in a growing switch. I apply it where change actually happens repeatedly. A small, stable switch (or a switch expression over a closed set) is fine; building extension points for variants that never arrive is speculative generality.
I do not abstract when there is no second variant, no boundary to protect and no testing need, because an abstraction costs indirection, a name, a contract and cognitive load. Typical examples are an IOrderService with one implementation used by one controller, a generic repository over EF Core, or a wrapper around HttpClient or ILogger<T>, which are already abstractions. I do abstract at architecture boundaries (ports for payment vendors, email, storage) and where tests need a seam for something slow or non-deterministic. If an abstraction has had one implementation and one caller for a long time and is not at a boundary, I inline it.
How to tell it (STAR)
**S:** At [company], our checkout priced shipping through one large switch, and a release adding a new carrier silently overcharged express parcels for an existing carrier. **T:** I had to stop the overcharging, refund customers and make sure a new carrier could never change another carrier's prices. **A:** I rolled back, used Application Insights quote logs to size the impact, and found the shared `surcharge` variable in the diff. Then I pinned every carrier's prices with characterisation tests, extracted one strategy class per carrier with a context that selects by key and fails fast on duplicates, and added a registration test. **R:** We refunded [N] orders within [a day], and the next three carriers each shipped as one class and one registration line with zero pricing incidents over [the following year].
Last updated 18 Nov 2026.