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

πŸ“š Interview question

Refactor this shipping cost calculator: a long switch on carrier (AusPost, StarTrack, DHL) that every new carrier edits, with rates hard-coded inside. Turn it into strategies selected by key and registered in DI, show how the result satisfies Open/Closed, how you test it, and when you would leave the switch alone.

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.

Mid-Level Coding Intermediate dependency-injection design-patterns open-closed refactoring strategy unit-testing

🎯 Key points

  • Write characterisation (golden-master) tests over the existing switch before changing it, so the refactor is provably behaviour-preserving
  • IShippingStrategy exposes a Carrier key and Calculate(Parcel); one class per carrier with its own dependencies (rates via IOptions<T>, remote-area lookup)
  • The context takes IEnumerable<IShippingStrategy> and builds a dictionary once; ToDictionary throws on a duplicate key, so mistakes fail at start-up
  • Unknown carriers return a validation error (TryCalculate / 400 problem details) and are logged with the carrier value, not a NullReferenceException or a zero price
  • Open/Closed: a new carrier is one new class plus one registration line; existing carriers and the context are untouched, so a change can't alter another carrier's price
  • Tests: one per strategy, one for the context with fake strategies, and one that builds the real container and asserts every expected carrier is registered
  • Rate changes are configuration, not code: version rates with an effective date so old quotes stay reproducible, and ship that separately from the Strategy refactor
  • Leave the switch alone when there are two or three stable carriers with one-line formulas

⏱ 30-second 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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"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 IShippingStrategy interface with a Carrier key and Calculate(Parcel), and move each case into its own class: AusPostStrategy, StarTrackStrategy, DhlStrategy. Each class takes only what it needs: AusPost gets its rates through IOptions<AusPostRates>, StarTrack also gets an IRemoteAreaLookup for 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 by Carrier. ToDictionary throws 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 a TryCalculate false and a 400, not a null reference. For Open/Closed, adding Sendle means one new class and one AddSingleton<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 new the 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."


The refactor, step by step

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

Before and after

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

When to leave the switch

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

Production example

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.

πŸ” What the interviewer is checking

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

  • Starts with characterisation tests.
  • Builds the lookup once and fails fast on duplicate keys.
  • Handles unknown carriers as a validation error.
  • Tests the real registration, not only the classes.
  • Says when they'd keep the switch.

Red flags

  • Replaces the switch with a switching factory.
  • No tests, or fixes behaviour during the refactor.
  • Calls everything Open/Closed without saying what stays unchanged.

πŸ“š Learn in depth

1. Why refactor this switch at all

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.

2. Characterisation tests first

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.

3. Structure after the refactor

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

4. The context's responsibilities

  • Selection: one dictionary lookup, case-insensitive because keys arrive from URLs and JSON.
  • Fail fast: 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.
  • Unknown keys: TryCalculate returns false; the endpoint returns a 400 with a problem-details body.
  • Enumeration: exposing Carriers lets the UI list supported carriers from the same source of truth.

5. Open/Closed, honestly

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.

6. Strategies vs data

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.

7. Testing layers

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

Try it yourself

  1. Write a characterisation [Theory] over the original switch with at least 10 rows per carrier.
  2. Extract the three strategies and run the same tests without changing them.
  3. Add a fourth carrier and count the files changed (target: two).
  4. Register two strategies with the same key and confirm start-up fails.
  5. Replace two carriers that differ only in numbers with one table-driven strategy and compare.

πŸ’» Code

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

⚠ Common mistakes

  • Mistake: Refactoring before writing characterisation tests. Why it is wrong: Pricing changes silently and nobody notices until finance reconciles. Instead: Pin current outputs with a table-driven test first, then refactor under it.
  • Mistake: Replacing the switch with a factory that switches on carrier to 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.
  • Mistake: Scanning 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.
  • Mistake: Returning 0 or throwing 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.
  • Mistake: Fixing pricing bugs during the refactor. Why it is wrong: Reviewers can't tell intended changes from accidental ones. Instead: Refactor first with behaviour unchanged, then fix bugs in a separate change with their own tests.
  • Mistake: A class per carrier when carriers differ only in numbers. Why it is wrong: Duplicated code where data would do. Instead: One table-driven strategy configured per carrier, with separate classes only for different logic.
  • Mistake: Refactoring a two-case switch that hasn't changed in years. Why it is wrong: More files, no risk reduced. Instead: Leave it; revisit when the third and fourth carriers arrive.

πŸ› Senior insight: trade-offs

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.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions keyed services or resolving a strategy from the provider Why: Checks keyed services and avoiding the service locator when choosing implementations at run time
    How to answer

    This is a Strategy (IPaymentGateway) chosen by a factory. There are three DI-friendly ways to do it:

    • Keyed services (.NET 8+): 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.
    • Typed resolver over keyed services: 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.

  2. When: Candidate claims the refactor satisfies Open/Closed Why: Checks that Open/Closed is applied pragmatically, not as speculative extension points
    How to answer

    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.

  3. When: Candidate would refactor every switch into strategies Why: Checks judgement about over-abstraction
    How to answer

    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.

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

Adding a carrier overcharged express parcels for an existing one
Situation
Checkout service for [retailer], about [8,000] orders a day across three carriers. Shipping cost came from a single 180-line switch. A release added a fourth carrier.
Signals
Finance reconciliation showed express shipping revenue [~$7.50 per parcel] above carrier invoices for [two days]. A handful of customer complaints about express prices. No errors or alerts: the code worked, the number was wrong.
Investigation
Compared quote logs in Application Insights (custom dimension `carrier`, `express`, `cost`) before and after the release. `git diff` showed the new case reused a `surcharge` local declared above the switch, and the existing carrier's path now read it. Reproduced with a unit test using a parcel from the logs.
Resolution
Immediate: rolled back the release and issued refunds for affected orders. Real fix: wrote characterisation tests over the old switch (30 rows per carrier), extracted one `IShippingStrategy` per carrier, built the context's dictionary once, and re-added the new carrier as its own class.
Prevention
Golden-master tests per carrier run in CI; a registration test asserts the carrier set; quotes are compared nightly against carrier invoices with an alert at [2%] variance; an ADR records that new carriers are new classes only.

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

↩ Usually asked after

More in Behavioral Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

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