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

📚 Interview question

An Invoice class switches on its Kind in five different methods. How would you replace the type code with polymorphism, when is a dictionary of strategies or a single switch expression the better choice, and when should you leave the conditional alone?

Applies Replace Conditional with Polymorphism to an invoice type code repeated across methods, compares subclasses, a dictionary of strategies and switch expressions, and covers the expression problem, EF Core inheritance mapping and when to keep the switch.

Mid-Level Coding Intermediate code-quality ef-core polymorphism refactoring strategy-pattern switch-expression

🎯 Key points

  • A single switch is fine; the smell is the same switch on the same type code repeated in several places
  • Replace Conditional with Polymorphism: one subclass (or strategy) per case; each switch arm becomes an override
  • If the kind can change at run time (proforma becomes standard), don't use subclasses: keep one entity and a dictionary of strategies
  • Policies should be stateless singletons; per-request state is passed in, never stored on the policy
  • Expression problem: polymorphism makes new types cheap and new operations expensive; switches the reverse
  • One switch expression in one place, especially over a small closed set, is often clearer than a strategy dictionary
  • Persisting a hierarchy: EF Core TPH with a discriminator column, and the type is fixed for life
  • Performance is rarely the decider: a virtual call or dictionary lookup costs nanoseconds; readability and change frequency decide

⏱ 30-second answer

The smell isn't the switch; it's the same switch on the same type code repeated in CalculateTax, DueDate, CanCancel and two more places, so adding a kind means hunting for every one. Replace Conditional with Polymorphism gives each kind its own subclass (or policy object), and each switch arm becomes an override, so a new kind is one new class and the compiler forces every abstract member to be implemented.

If the data shape is the same for every kind, a dictionary of strategies keyed by the enum keeps one entity class and moves only the varying behaviour out. If there's one switch over a closed set, a switch expression is usually the clearest code you can write.

The trade-off is the expression problem: polymorphism makes adding kinds cheap and adding operations expensive; switches do the opposite.

🗣 Full answer (senior)

How I would answer this in an interview

"The first thing I'd say is that one switch isn't a problem. The problem here is that Invoice has an InvoiceKind field, and five methods all do switch (Kind) with Standard, CreditNote and Proforma arms. When the business adds a fourth kind, someone has to find all five, and the one they miss becomes a production bug. That's shotgun surgery caused by a type code.

Replace conditional with polymorphism fixes that by putting each kind's behaviour in one place. I'd make Invoice an abstract base with abstract members for the things that vary, and StandardInvoice, CreditNote and ProformaInvoice override them. I move one method at a time: make it abstract, paste each switch arm into the matching subclass, run the tests, commit. When the last switch is gone, the type code field is gone too, and adding a kind is a new class that won't compile until every abstract member is implemented.

But I'd only use subclasses if the kinds really differ in data or the hierarchy maps cleanly to persistence. With EF Core that means TPH, a discriminator column, and the kind can't change after creation. If it's one table and the kind can change, say a proforma becomes a standard invoice, I'd keep one entity and use a dictionary of policies: IReadOnlyDictionary<InvoiceKind, IInvoicePolicy>, registered in DI, so each policy is a small tested class and the entity stays simple.

The mistake I see is turning every switch into a class hierarchy. If there's one switch, in one place, over a set that rarely changes, a switch expression is the most readable code and the compiler warns me if a case is missing. Polymorphism earns its keep when the same decision is repeated."


Three ways to remove the repeated switch

Option Shape Adding a kind Adding an operation Best when
Subclasses abstract class Invoice + sealed subclasses New class Edit every subclass Kinds differ in data and behaviour; kind is fixed for life
Strategy dictionary One entity + IInvoicePolicy per kind New policy + registration Edit every policy Same data, varying rules; kind can change; rules need DI services
Switch expression Kind switch { ... } in one place Edit the switch (compiler warns) New switch One decision point, small closed set
Leave it Existing if/switch n/a n/a One occurrence, stable, readable

Persistence consequences (EF Core)

Mapping What it means Watch out for
TPH (default) One table, discriminator column Nullable columns for subclass-only data; can't change type in place
TPT Table per type, joins Slower queries on the base type
TPC Table per concrete type Key generation across tables; unions on base queries
No inheritance One entity, policy by Kind Keep policies stateless and tested

Production example

In an accounts-receivable service, the InvoiceKind switch appeared in 7 places across 4 classes. Moving to a policy dictionary took 6 small PRs over a week; when "recurring invoice" was added three months later it was one new 60-line policy class and one DI line, with no edits to existing kinds and no regressions, against two production bugs from the previous kind added the old way.

🔍 What the interviewer is checking

Checks that the candidate can perform Replace Conditional with Polymorphism on real code and has the judgement to know when a switch is the better design.

Green flags

  • Identifies the repeated switch, not the switch itself, as the smell
  • Offers subclasses, strategy dictionary and switch expression with criteria
  • Mentions the expression problem or the 'which axis changes' question
  • Considers EF Core persistence and whether the kind can change
  • Plans the change one method at a time with tests

Red flags

  • "Switch statements are always bad"
  • Puts DI services inside entity subclasses
  • Silent default arms

📚 Learn in depth

1. Why a repeated type code hurts

A type code (an enum or string field that says what "kind" an object is) forces every behaviour that depends on the kind to branch on it. Each switch is a copy of the same knowledge: the list of kinds.

  CalculateTax  switch(Kind) { Standard, CreditNote, Proforma }
  DueDate       switch(Kind) { Standard, CreditNote, Proforma }
  CanCancel     switch(Kind) { Standard, CreditNote, Proforma }
  Render        switch(Kind) { Standard, CreditNote, Proforma }
  Post          switch(Kind) { Standard, CreditNote, Proforma }
                               + Recurring?  -> 5 edits, 1 easily missed

2. Virtual dispatch replaces the branch

With polymorphism, the runtime chooses the code through the object's method table: a call to invoice.CalculateTax() loads the type's vtable slot and jumps there. The knowledge "which kinds exist" now lives in the type system, once.

           Invoice (abstract)
          /        |         \
 StandardInvoice CreditNote ProformaInvoice
   Tax()          Tax()       Tax()
   DueDate()      DueDate()   DueDate()

Cost: a virtual call is a few nanoseconds and the JIT can often devirtualise calls on sealed types (and guarded devirtualisation with PGO handles the common case), so performance is rarely a reason either way.

3. The expression problem

Data types and operations form a grid. Object-oriented polymorphism groups the grid by type (each class holds all operations for that type); functional pattern matching groups it by operation (each function handles all types).

               Tax   DueDate  CanCancel  (new op?)
  Standard      x       x        x
  CreditNote    x       x        x
  Proforma      x       x        x
  (new kind?)

New rows are cheap with classes; new columns are cheap with switches. Pick the axis that changes more often in your domain. Invoice kinds that change yearly but new operations weekly argue for switches (or a visitor); the reverse argues for classes.

4. Strategy dictionary mechanics

Keeping one entity and moving behaviour to policy objects separates what the invoice is (data, persisted) from how it's treated (rules, possibly needing services such as a clock or tax-rate provider). In .NET 8+ you can register keyed services (AddKeyedSingleton<IInvoicePolicy, CreditNotePolicy>(InvoiceKind.CreditNote)) or build a dictionary from IEnumerable<IInvoicePolicy>. Validate at start-up that every enum value has a policy so a missing one fails fast, not on the first credit note.

5. Doing it safely

  1. Characterisation tests per kind for each switching method.
  2. Introduce the base type or policy interface with one member.
  3. Move one switch: each arm into its class; the old method delegates.
  4. Tests, commit. Repeat for the next switch.
  5. Delete the enum switches and, for subclasses, the type code field (EF Core keeps its own discriminator).

Try it yourself

  1. Count the switches on a type code in your codebase with a regex search (switch \(.*Kind\)).
  2. Convert one to a policy dictionary and add a start-up check that every enum value has a policy.
  3. Map a small hierarchy with EF Core TPH and inspect the generated table and discriminator.
  4. Benchmark a switch versus a virtual call on a sealed type with BenchmarkDotNet; note how small the difference is.

💻 Code

Before: the same switch on Kind in several methods.

namespace Billing;

public enum InvoiceKind { Standard, CreditNote, Proforma }

public sealed class InvoiceBefore
{
    public required InvoiceKind Kind { get; init; }
    public required decimal Subtotal { get; init; }
    public required DateOnly IssuedOn { get; init; }

    public decimal Gst() => Kind switch
    {
        InvoiceKind.Standard => Math.Round(Subtotal * 0.10m, 2),
        InvoiceKind.CreditNote => -Math.Round(Subtotal * 0.10m, 2),
        InvoiceKind.Proforma => 0m,   // not a tax invoice
        _ => throw new ArgumentOutOfRangeException(nameof(Kind), Kind, null)
    };

    public DateOnly? DueOn() => Kind switch
    {
        InvoiceKind.Standard => IssuedOn.AddDays(30),
        InvoiceKind.CreditNote => null,
        InvoiceKind.Proforma => IssuedOn.AddDays(7),
        _ => throw new ArgumentOutOfRangeException(nameof(Kind), Kind, null)
    };

    public bool CanCancel(bool isPaid) => Kind switch
    {
        InvoiceKind.Standard => !isPaid,
        InvoiceKind.CreditNote => false,
        InvoiceKind.Proforma => true,
        _ => throw new ArgumentOutOfRangeException(nameof(Kind), Kind, null)
    };
}

After (option A): a dictionary of policies, keeping one persisted entity. Each kind's rules are together and testable.

namespace Billing;

public sealed class Invoice
{
    public required InvoiceKind Kind { get; set; }    // can change: proforma -> standard
    public required decimal Subtotal { get; init; }
    public required DateOnly IssuedOn { get; init; }
}

public interface IInvoicePolicy
{
    InvoiceKind Kind { get; }
    decimal Gst(Invoice invoice);
    DateOnly? DueOn(Invoice invoice);
    bool CanCancel(Invoice invoice, bool isPaid);
}

public sealed class StandardPolicy : IInvoicePolicy
{
    public InvoiceKind Kind => InvoiceKind.Standard;
    public decimal Gst(Invoice i) => Math.Round(i.Subtotal * 0.10m, 2);
    public DateOnly? DueOn(Invoice i) => i.IssuedOn.AddDays(30);
    public bool CanCancel(Invoice i, bool isPaid) => !isPaid;
}

public sealed class CreditNotePolicy : IInvoicePolicy
{
    public InvoiceKind Kind => InvoiceKind.CreditNote;
    public decimal Gst(Invoice i) => -Math.Round(i.Subtotal * 0.10m, 2);
    public DateOnly? DueOn(Invoice i) => null;
    public bool CanCancel(Invoice i, bool isPaid) => false;
}

public sealed class ProformaPolicy : IInvoicePolicy
{
    public InvoiceKind Kind => InvoiceKind.Proforma;
    public decimal Gst(Invoice i) => 0m;
    public DateOnly? DueOn(Invoice i) => i.IssuedOn.AddDays(7);
    public bool CanCancel(Invoice i, bool isPaid) => true;
}

public sealed class InvoicePolicies
{
    private readonly IReadOnlyDictionary<InvoiceKind, IInvoicePolicy> _byKind;

    public InvoicePolicies(IEnumerable<IInvoicePolicy> policies)
    {
        _byKind = policies.ToDictionary(p => p.Kind);
        // Fail at start-up, not on the first credit note, if a kind has no policy.
        var missing = Enum.GetValues<InvoiceKind>().Where(k => !_byKind.ContainsKey(k)).ToList();
        if (missing.Count > 0)
            throw new InvalidOperationException($"No invoice policy for: {string.Join(", ", missing)}");
    }

    public IInvoicePolicy For(Invoice invoice) => _byKind[invoice.Kind];
}
// Program.cs
builder.Services.AddSingleton<IInvoicePolicy, StandardPolicy>();
builder.Services.AddSingleton<IInvoicePolicy, CreditNotePolicy>();
builder.Services.AddSingleton<IInvoicePolicy, ProformaPolicy>();
builder.Services.AddSingleton<InvoicePolicies>();

// Usage: var gst = policies.For(invoice).Gst(invoice);

Option B, when kinds differ in data and never change type: public abstract class Invoice { public abstract decimal Gst(); ... } with sealed class CreditNote : Invoice, mapped with EF Core TPH (modelBuilder.Entity<Invoice>().HasDiscriminator<string>("Kind")).

⚠ Common mistakes

  • Mistake: Turning every switch into a class hierarchy. Why it is wrong: one switch in one place is already the single source of truth; a hierarchy adds types and indirection for no gain. Instead: refactor when the same decision is repeated, or when each case grows large.
  • Mistake: Using subclasses when the kind can change at run time. Why it is wrong: an object can't change its class; with EF Core TPH you'd need to delete and re-insert or hack the discriminator. Instead: keep one entity and attach policies by kind (State or Strategy).
  • Mistake: Leaving a default arm that silently returns a value. Why it is wrong: a new kind gets wrong tax or due dates with no error. Instead: make base members abstract, or throw in the discard arm and check policy coverage at start-up.
  • Mistake: Putting service dependencies (repositories, HTTP clients) into entity subclasses. Why it is wrong: entities are created by EF Core without DI, so you end up with service locators. Instead: keep entities pure; put rules needing services in DI-registered policies.
  • Mistake: Doing the whole conversion in one PR. Why it is wrong: five methods times three kinds is a big, risky diff. Instead: one method per commit, old switch delegating until the last one.
  • Mistake: Ignoring the expression problem. Why it is wrong: if new operations arrive more often than new kinds, a hierarchy makes every change touch every class. Instead: choose the axis that changes most often.
  • Mistake: Building the dictionary on every call. Why it is wrong: allocations and repeated validation in a hot path. Instead: build once in a singleton.

🏛 Senior insight: trade-offs

This refactoring is about where knowledge lives. Polymorphism puts "what a credit note does" in one class; a switch expression puts "how tax works for every kind" in one function. Both are fine; the repeated switch is the bad option, because it spreads one list of kinds across the codebase.

I decide by asking two questions: which axis changes more often (kinds or operations), and is the kind fixed for an object's lifetime? In practical terms: if next quarter's backlog has "add a recurring invoice", I want kinds to be cheap (classes or policies); if it has "add a late-fee rule, a reminder date and a PDF layout" for the existing kinds, I want operations to be cheap (switches in one place each). If the kind can change at run time, subclasses are out and policies win.

Policies in a dictionary should be stateless singletons: anything per-invoice is passed as a parameter. A policy that caches the last invoice or holds a scoped DbContext becomes a thread-safety bug or a captive dependency once it's registered as a singleton. If a policy needs scoped services, register the policies as scoped too, or pass the data in.

Performance rarely decides it: a switch on a small enum compiles to a jump table, a virtual call on a sealed type is often devirtualised, and a dictionary lookup is tens of nanoseconds. Measure with BenchmarkDotNet only if the code is in a hot loop.

Option When it fits Cost When not to
Subclasses + TPH Kinds differ in data; type fixed for life; new kinds common Hierarchy, discriminator, nullable columns Kind changes over time; operations change more than kinds
Policy dictionary / keyed services Same data, varying rules, rules need DI; kind may change Interface + one class per kind Two kinds with one-line differences: a switch is clearer
Switch expression One decision point, closed set None Same switch repeated in many places
Visitor Stable hierarchy, frequently added operations Boilerplate, double dispatch Hierarchy changes often

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions strategies registered in DI Why: Checks they can implement keyed strategy selection and test it
    How to 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.

  2. When: Candidate says the change makes the code open for extension Why: Checks they understand Open/Closed without building speculative plug-in frameworks
    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 chooses a class hierarchy Why: Checks their judgement between inheritance and composition
    How to answer

    Default to composition: build behaviour from small objects behind interfaces and inject them. It keeps coupling low, lets behaviour change at run time and is easy to test. Use inheritance only when all of these hold: there is a true is-a relationship where every subtype can substitute for the base (Liskov), the base was designed for extension (documented virtual hooks, protected constructor), there is one axis of variation, and you want to share state plus a fixed algorithm (template method). Framework extension points such as BackgroundService, DelegatingHandler and DbContext are good inheritance cases. When a hierarchy explodes or subclasses override things to throw NotSupportedException, refactor by extracting the varying behaviour into strategies and composing them.

🛠 Real-world problems: how you handle them

A missed switch arm billed credit notes with positive GST
Situation
An accounts-receivable service for [n] business customers branched on `InvoiceKind` in [7] places. The team added a new 'adjustment' kind for [business reason] by [date].
Signals
Finance reconciliation flagged that the monthly BAS GST total was off by [amount]; [n] adjustment invoices showed positive GST in reports where it should have been negative.
Investigation
Searched the solution for `switch (invoice.Kind)` and `Kind ==` comparisons, found two places where the new kind fell to a `default` arm, and used git blame to confirm the feature PR edited only five of the seven.
Resolution
Hotfixed the two arms and reissued the affected invoices. Then replaced the scattered switches with a policy dictionary built from DI, with a start-up check that every `InvoiceKind` has a policy, migrated one method per PR.
Prevention
Start-up validation of policy coverage, unit tests per policy, an analyser rule (or code review checklist) against new `switch` statements on `InvoiceKind` outside the policies, and characterisation tests on BAS totals.

How to tell it (STAR)

**S:** Our accounts-receivable service had the invoice-kind switch in seven places, and when we added an adjustment kind, two were missed and fell to a default arm. **T:** I was asked to fix the incorrect GST and stop it happening again. **A:** I hotfixed the two arms and worked with finance to reissue [n] invoices. Then I moved each kind's rules into a policy class registered in DI, with a start-up check that fails if any kind lacks a policy, migrating one method per PR behind characterisation tests. **R:** The next new kind, [recurring], was one 60-line class and a DI line, shipped in [days], and we've had zero kind-related GST errors since [date].

↩ Usually asked after

More in Refactoring

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me