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.
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.
"The first thing I'd say is that one switch isn't a problem. The problem here is that
Invoicehas anInvoiceKindfield, and five methods all doswitch (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
Invoicean abstract base with abstract members for the things that vary, andStandardInvoice,CreditNoteandProformaInvoiceoverride 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."
| 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 |
| 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 |
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.
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
Red flags
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
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.
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.
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.
switch \(.*Kind\)).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")).
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.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 |
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.
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.
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.
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].
Last updated 23 Nov 2026.