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

📚 Interview question

A CreateInvoice method takes nine parameters and its body is nested five levels deep in if statements. How would you refactor it with introduce parameter object, guard clauses and pattern matching, and what traps should you avoid?

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.

Intermediate Coding Intermediate code-quality csharp guard-clauses parameter-object pattern-matching refactoring

🎯 Key points

  • Introduce Parameter Object: group parameters that travel together into an immutable record
  • Parameter object must be a real concept (InvoiceRequest, BillingPeriod), not a grab bag
  • Guard clauses: invert conditions and return or throw early to flatten nesting
  • Keep the original validation order, or behaviour (which error is reported) changes
  • Replace boolean flag parameters with enums or separate methods
  • Switch expressions and property/relational patterns replace if-else ladders; compiler warns on non-exhaustive switches (CS8509)
  • Public signature change: keep an [Obsolete] overload that delegates, so callers in other assemblies don't break
  • Characterisation tests per error path before, and one step per commit

⏱ 30-second answer

Three refactorings, in order, with tests green between each:

  • Introduce Parameter Object: parameters that always travel together (customer id, name, email; issue date and terms) become an immutable record such as InvoiceRequest. Call sites get shorter and the group gets a name.
  • Guard clauses: invert each if and return or throw early, so the happy path runs down the left margin instead of five levels in.
  • Pattern matching: replace 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 record like InvoiceRequest, with the customer details as their own CustomerRef record. 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 like isTaxExempt I'd turn into an enum, because CreateInvoice(..., true, false) tells the reader nothing.

Next the nesting. Each if (valid) { ... } becomes if (!valid) return Failure(...) or a throw, so the rest of the method reads straight down. .NET has helpers like ArgumentNullException.ThrowIfNull and ArgumentOutOfRangeException.ThrowIfNegativeOrZero for 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 silent else.

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


The three refactorings

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

Guards: throw or return?

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

Production example

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.

🔍 What the interviewer is checking

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

  • Groups parameters by concept, using records
  • Notices validation order is behaviour
  • Replaces boolean flags with enums
  • Uses switch expressions with a discard arm and knows CS8509
  • Distinguishes throw (programmer error) from result (business rule)

Red flags

  • One giant context object
  • Reorders logic and calls it a refactoring
  • No tests before starting

📚 Learn in depth

1. Data clumps and parameter objects

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

2. Why guard clauses flatten code

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.

3. Switch expressions and exhaustiveness

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.

4. Argument guards in .NET

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

Try it yourself

  1. Measure the cyclomatic complexity of a nested method (Visual Studio Analyze → Calculate Code Metrics), refactor with guards, measure again.
  2. Remove an enum arm from a switch expression and read CS8509.
  3. Reorder two guards and see whether your characterisation tests catch it.
  4. Print a record containing an email address with ToString() and decide whether it should be logged.

💻 Code

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.

⚠ Common mistakes

  • Mistake: Reordering guard clauses "for neatness". Why it is wrong: when several inputs are invalid, a different error is returned, which changes the API response. Instead: keep the original order; change it deliberately in a separate commit.
  • Mistake: Changing a public method's signature in one step. Why it is wrong: callers in other assemblies, NuGet consumers or reflection-based code break at compile or run time, and a parameter object is a binary-breaking change. Instead: add the new overload, keep the old one as an [Obsolete] wrapper that builds the record and delegates, migrate callers, then delete it.
  • Mistake: Creating a parameter object that holds everything (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).
  • Mistake: Making the parameter object a mutable class. Why it is wrong: callees can change the caller's data, a hidden side effect. Instead: use a record with init-only or positional properties.
  • Mistake: Keeping 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.
  • Mistake: Writing a switch expression on an enum with no discard arm. Why it is wrong: undefined enum values throw SwitchExpressionException with an unhelpful message. Instead: add _ => throw new ArgumentOutOfRangeException(...) with the value.
  • Mistake: Throwing exceptions for expected business validation. Why it is wrong: exceptions are costly and hide normal control flow. Instead: validate input shape at the edge (FluentValidation or DataAnnotations, returning a 400 ValidationProblemDetails), return a result for business rules inside, and throw only for programmer errors via ThrowIfNull, ThrowIfNullOrWhiteSpace and friends.
  • Mistake: Logging the new record with its default 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.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate uses a switch expression or pattern matching Why: Checks they understand expression versus statement and the patterns available
    How to answer

    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.

  2. When: Candidate talks about guard clauses that throw Why: Checks they know where failing fast helps and where it makes the system fragile
    How to answer

    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.

🛠 Real-world problems: how you handle them

Guard reordering changed the API's validation response
Situation
A billing API used by [n] partner integrations had a 140-line `CreateInvoice` with nine parameters. A developer refactored it for a new purchase-order rule due [date].
Signals
After the refactor, a contract test from [partner] failed: an invoice missing both customer id and a positive subtotal now returned 'Subtotal must be positive' instead of 'Customer is required'.
Investigation
Compared the before/after diffs commit by commit, ran the characterisation suite against each commit to find the first failing one, and checked the partner's integration logs for which error codes they parse.
Resolution
Reverted the guard order in the refactoring commit so it matched the original, then raised a separate, documented change for the order the team actually wanted, with partner notice.
Prevention
Characterisation tests for every validation error path, contract tests with partners in CI, and a PR checklist item: 'refactoring commits contain no behaviour change'.

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.

More in Refactoring

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me