Refactors a long-parameter, deeply nested invoice method using Introduce Parameter Object (a record), guard clauses and switch expressions, and covers the traps: changed validation order, bag-of-everything parameter objects, boolean flags and non-exhaustive switches.
Three refactorings, in order, with tests green between each:
InvoiceRequest. Call sites get shorter and the group gets a name.if and return or throw early, so the happy path runs down the left margin instead of five levels in.if/else ladders that choose a value with a switch expression, which is shorter and lets the compiler warn when a case is missing.The traps: changing which validation error fires first, building a parameter object that is just a bag of unrelated fields, and keeping boolean flag parameters. The trade-off: a parameter object adds a type, so use it when the group is a real concept.
"First I'd write characterisation tests over a handful of invoices, including the ones that fail validation, and assert which error message comes back, because validation order is behaviour.
Then I'd look at the nine parameters. Usually they fall into groups: who the customer is, when the invoice is issued and due, and what's being billed. A group that always travels together is a missing concept, so I'd introduce a parameter object, an immutable
recordlikeInvoiceRequest, with the customer details as their ownCustomerRefrecord. Rider and Visual Studio can do the mechanical part: Rider has Transform Parameters, and in Visual Studio I use Change Signature plus the compiler. Boolean parameters likeisTaxExemptI'd turn into an enum, becauseCreateInvoice(..., true, false)tells the reader nothing.Next the nesting. Each
if (valid) { ... }becomesif (!valid) return Failure(...)or athrow, so the rest of the method reads straight down. .NET has helpers likeArgumentNullException.ThrowIfNullandArgumentOutOfRangeException.ThrowIfNegativeOrZerofor programmer errors; business validation returns a result. Finally, the bit that picks payment terms from customer type and amount becomes a switch expression with property and relational patterns, and I rely on the compiler warning for a missing case rather than a silentelse.The mistake I see is the 'refactoring' that reorders the guards because it looks neater, and suddenly a missing email is reported before an invalid amount. The API's error response changed, so it wasn't a refactoring. Keep the order, or change it deliberately in a separate commit."
| Refactoring | Smell it removes | Mechanism | Watch out for |
|---|---|---|---|
| Introduce Parameter Object | Long parameter list, data clumps | record grouping co-travelling values |
Grab-bag objects; mutable classes |
| Replace Nested Conditional with Guard Clauses | Arrow code | Invert condition, return/throw early | Validation order; resource cleanup |
| Replace Conditional with switch expression | if/else ladders choosing a value | Property, relational, and/or patterns |
Missing _ arm or wrong order of arms |
| Replace Flag Argument | Boolean parameters | Enum or two methods | Enum with only two values that will never grow: two methods may be clearer |
| Failure | Use | Example |
|---|---|---|
| Programmer error (null argument) | throw via ThrowIfNull |
ArgumentNullException.ThrowIfNull(request) |
| Expected business rule | Return a result / validation error | Amount over credit limit |
| Invalid input at the API edge | Validator (FluentValidation, DataAnnotations) before the method | Malformed email |
In a billing API, the CreateInvoice refactor (parameter object, guards, one switch expression) cut the method from 140 to 45 lines and its cyclomatic complexity from 23 to 8. Characterisation tests over 25 cases caught one reordered guard during the refactor that would have changed the 400 response for invoices missing a purchase order.
Checks that the candidate can apply three everyday refactorings to real code while preserving behaviour, and knows modern C# features that make them clean.
Green flags
Red flags
When the same three or four values appear together in several signatures, they are a data clump: a concept the code hasn't named. Naming it gives you somewhere to put behaviour later (BillingTerms.DueDate(issueDate)), and the compiler stops you passing issueDate and dueDate in the wrong order.
CreateInvoice(customerId, customerName, email, issueDate, termsDays,
subtotal, currency, isTaxExempt, purchaseOrder)
|
v
CreateInvoice(InvoiceRequest request)
InvoiceRequest(CustomerRef Customer, DateOnly IssueDate, Money Subtotal,
TaxTreatment Tax, string? PurchaseOrder)
Records give value equality, immutability with positional properties, with expressions for tests, and ToString() for logs (be careful: the generated ToString prints every property, including personal data).
Nested conditionals force the reader to keep a stack of conditions in their head. Guard clauses handle each exceptional case and leave, so after line N the reader knows all previous conditions held.
nested guards
if a if !a return E1
if b if !b return E2
if c if !c return E3
happy path happy path
else E3
else E2
else E1
Equivalence holds only if each branch's result is the same: map every else to its guard carefully. In a method with a try/finally or using, early returns still run the cleanup, which is usually what you want.
A switch expression must produce a value for every input. If the compiler can prove inputs are unhandled (for example, an enum value without an arm and no discard), it warns with CS8509. Enums can hold undefined values at run time, so the compiler still expects a _ arm, or throws SwitchExpressionException if none matches. Arms are evaluated top to bottom: put specific patterns ({ Type: Government, Subtotal.Amount: > 10_000m }) before general ones.
.NET 6 added ArgumentNullException.ThrowIfNull, .NET 7 ArgumentException.ThrowIfNullOrEmpty, and .NET 8 ArgumentOutOfRangeException.ThrowIfNegative, ThrowIfNegativeOrZero, ThrowIfGreaterThan and ArgumentException.ThrowIfNullOrWhiteSpace. They use CallerArgumentExpression so the parameter name is filled in for you.
ToString() and decide whether it should be logged.Before: nine parameters, a flag argument and arrow-shaped nesting.
namespace Billing;
public sealed record Invoice(string CustomerId, decimal Total, DateOnly DueDate, string? PurchaseOrder);
public sealed record InvoiceResult(Invoice? Invoice, string? Error);
public sealed class InvoiceServiceBefore
{
public InvoiceResult CreateInvoice(string customerId, string customerName, string email,
DateOnly issueDate, int termsDays, decimal subtotal, string currency,
bool isTaxExempt, string? purchaseOrder)
{
if (!string.IsNullOrWhiteSpace(customerId))
{
if (subtotal > 0)
{
if (currency == "AUD")
{
if (termsDays > 0)
{
var gst = isTaxExempt ? 0 : Math.Round(subtotal * 0.10m, 2);
return new(new Invoice(customerId, subtotal + gst,
issueDate.AddDays(termsDays), purchaseOrder), null);
}
else return new(null, "Terms must be positive");
}
else return new(null, "Only AUD is supported");
}
else return new(null, "Subtotal must be positive");
}
else return new(null, "Customer is required");
}
}
After: a parameter object, an enum instead of the flag, guards in the same order, and a switch expression for the tax.
namespace Billing;
public enum TaxTreatment { Standard, Exempt }
public sealed record CustomerRef(string Id, string Name, string Email);
public sealed record InvoiceRequest(
CustomerRef Customer,
DateOnly IssueDate,
int TermsDays,
decimal Subtotal,
string Currency,
TaxTreatment Tax,
string? PurchaseOrder);
public sealed class InvoiceService
{
public InvoiceResult CreateInvoice(InvoiceRequest request)
{
ArgumentNullException.ThrowIfNull(request); // programmer error: throw
// Business rules: same order as before, so the same error wins.
if (string.IsNullOrWhiteSpace(request.Customer.Id)) return Fail("Customer is required");
if (request.Subtotal <= 0) return Fail("Subtotal must be positive");
if (request.Currency != "AUD") return Fail("Only AUD is supported");
if (request.TermsDays <= 0) return Fail("Terms must be positive");
var gst = request.Tax switch
{
TaxTreatment.Exempt => 0m,
TaxTreatment.Standard => Math.Round(request.Subtotal * 0.10m, 2),
_ => throw new ArgumentOutOfRangeException(nameof(request), request.Tax, "Unknown tax treatment")
};
var invoice = new Invoice(request.Customer.Id, request.Subtotal + gst,
request.IssueDate.AddDays(request.TermsDays), request.PurchaseOrder);
return new InvoiceResult(invoice, null);
}
private static InvoiceResult Fail(string error) => new(null, error);
}
Note Math.Round(x, 2) uses banker's rounding (MidpointRounding.ToEven) in both versions; changing it to AwayFromZero would be a behaviour change and belongs in its own commit.
[Obsolete] wrapper that builds the record and delegates, migrate callers, then delete it.InvoiceContext with 20 properties). Why it is wrong: it hides the long parameter list instead of naming concepts, and every method gets fields it doesn't need. Instead: group by concept (customer, billing period, amount).record with init-only or positional properties.bool isTaxExempt in the new signature. Why it is wrong: call sites read true, false with no meaning, and a third case later forces another bool. Instead: an enum or two separate methods.SwitchExpressionException with an unhelpful message. Instead: add _ => throw new ArgumentOutOfRangeException(...) with the value.ValidationProblemDetails), return a result for business rules inside, and throw only for programmer errors via ThrowIfNull, ThrowIfNullOrWhiteSpace and friends.ToString(). Why it is wrong: records print every property, which can leak personal information (Privacy Act 1988 / APP 11). Instead: log only identifiers, or override PrintMembers.These are small refactorings with a big effect on readability, and they're safe because they're mechanical, provided you respect the hidden behaviour: validation order, rounding mode, which exception type a caller catches. A characterisation test per error path is cheap insurance.
I also check whether the parameter object wants to become a domain type. If BillingTerms starts collecting DueDate() and IsOverdue(), that's the refactoring paying off; if it stays a passive bag that's fine for a request object at an API boundary.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Parameter object (record) | 4+ parameters with real groups; repeated across methods | One new type | Parameters genuinely unrelated; a single call site with 3 parameters |
| Builder | Many optional values, complex construction | More code | Simple required data: a record is enough |
| Guard clauses | Nested validation, arrow code | None | Complex branching where both sides are main paths |
| Switch expression | Choosing a value from a type/property | None | Branches with side effects and multiple statements |
An expression produces a value, like a + b or order.Total > 100; a statement does something, like if, foreach, return or a declaration. C# has become more expression-oriented: a switch expression returns a value, cannot fall through and warns if it is not exhaustive, and patterns (type, relational, property, list, and/or/not) let you test shape and values in one place. Expression-bodied members use => for one-line members, and throw expressions let ?? and ?: throw. I use expressions to compute values without mutation and statements when there are steps or side effects.
Fail fast means detecting a problem at the earliest point and stopping clearly, instead of carrying bad state forward until it causes a confusing failure later. In .NET that means guard clauses (ArgumentNullException.ThrowIfNull, ArgumentOutOfRangeException.ThrowIfNegativeOrZero), constructors that refuse invalid objects, nullable reference types, options validation with ValidateOnStart(), and DI ValidateOnBuild. It does not mean crashing on every transient error: inside a component I fail fast on programming and configuration errors, and at boundaries (network, other services) I use retries, timeouts and graceful degradation.
How to tell it (STAR)
**S:** Our billing API's `CreateInvoice` had nine parameters and five levels of nesting, and we needed to add a purchase-order rule. **T:** I wanted to make it readable first without changing any API behaviour for our [n] partners. **A:** I wrote characterisation tests for every error path, then introduced an `InvoiceRequest` record, swapped the tax flag for an enum and converted the nesting to guard clauses, one commit each. The tests caught that I'd reordered two guards, which would have changed the error returned for some partners, so I restored the order. **R:** The method went from [140] to [45] lines, the purchase-order rule was a [n]-line change, and there were zero partner-facing regressions.
Last updated 23 Nov 2026.