Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Cheat sheets: all cheat sheets

    Strategy or State? Interview Workbook

    Choose between pricing strategies and state transitions.

    strategy-state-interview-workbook.pdf3 pages · 105 KB
    Every page, in this page.

    When the Strategy pattern fits, when the State pattern fits, and when a plain function or a transition table is enough: six interview scenarios about pricing, order transitions, rounding, races and duplicate events.

    At a glance

    • Strategy: interchangeable algorithms or behaviors behind one contract, such as pricing policies. Choosing the policy is a separate step, done in one place.
    • State: what an object may do depends on where it is in its lifecycle, such as an order that must be paid before it ships. A rejected command leaves the state unchanged.
    • Start small: a function or a central transition table can be clearer than a family of classes. Add classes when the behavior per case grows.
    • A pattern organizes code; it does not make concurrent saves safe. Use a version check or a conditional update for that.
    • Name the business rule first, then the pattern. An interviewer wants the invariant and the trade-off, not a class diagram.

    Strategy or State?

    QuestionStrategyState
    What varies?which algorithm or behavior runswhich actions are allowed now
    Who picks the variant?a selector, from inputs such as customer or datethe object's own lifecycle position
    Typical examplestandard, loyalty and seasonal pricesPending, Paid, Shipped, Cancelled
    Lightweight forma function or a dictionary of functionsan enum and a transition table
    Classes help wheneach policy has its own data or ruleseach state has substantial behavior of its own

    Strategy: one contract, interchangeable calculations

    C#Runs
    using System.Globalization;
    CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
    
    Func<decimal, decimal> standard = subtotal => subtotal;
    Func<decimal, decimal> loyalty = subtotal => subtotal * 0.95m;
    (string Name, Func<decimal, decimal> Policy)[] policies =
    [
        ("standard", standard),
        ("loyalty", loyalty),
    ];
    foreach (var (name, policy) in policies)
        Console.WriteLine($"{name}: {Publish(policy, 200.00m)}");
    
    decimal tiny = 1.006m;
    Console.WriteLine($"checked before rounding: {standard(tiny) <= tiny}");
    decimal published = Publish(standard, tiny);
    Console.WriteLine($"published {published} <= {tiny}: {published <= tiny}");
    
    static decimal Publish(Func<decimal, decimal> policy, decimal subtotal) =>
        decimal.Round(policy(subtotal), 2, MidpointRounding.ToEven);
    Output
    standard: 200.00
    loyalty: 190.00
    checked before rounding: True
    published 1.01 <= 1.006: False
    • Each policy takes a subtotal and returns a price: one contract. The list is the single place that knows which policies exist; a real checkout selects one by name, for example from a dictionary. An interface with one class per policy is the same idea at a larger size.
    • "price never above the subtotal" held before rounding and failed after it: 1.006 became 1.01. Check the rule on the value you publish, and reject amounts with more than two decimal places before any policy runs.
    • Say the midpoint rule out loud. decimal.Round defaults to MidpointRounding.ToEven; pass MidpointRounding.AwayFromZero if the business expects 0.005 to become 0.01.
    C#Runs
    var order = new Order();
    Console.WriteLine(order.Apply(Command.Pay));
    Console.WriteLine(order.Apply(Command.Ship));
    Console.WriteLine(order.Apply(Command.Cancel));
    
    enum Status { Pending, Paid, Shipped, Cancelled }
    enum Command { Pay, Ship, Cancel }
    
    sealed class Order
    {
        static readonly Dictionary<(Status, Command), Status> Allowed = new()
        {
            [(Status.Pending, Command.Pay)] = Status.Paid,
            [(Status.Pending, Command.Cancel)] = Status.Cancelled,
            [(Status.Paid, Command.Ship)] = Status.Shipped,
        };
    
        public Status Status { get; private set; } = Status.Pending;
    
        public string Apply(Command command)
        {
            if (!Allowed.TryGetValue((Status, command), out Status next))
                return $"{command} rejected: still {Status}";
            Status before = Status;
            Status = next;
            return $"{command}: {before} -> {next}";
        }
    }
    Output
    Pay: Pending -> Paid
    Ship: Paid -> Shipped
    Cancel rejected: still Shipped
    • Every legal move is one line of the table, so each allowed and rejected transition is easy to test.
    • The setter is private: no caller can jump straight to Shipped and skip the rule.
    • A shipped order cannot be cancelled here. Returns and refunds are a separate business process, not a hidden extra transition.
    • Move to one class per state when each state carries real behavior of its own, not just a different set of allowed commands.

    Six scenarios, worked

    1. Checkout has standard, loyalty and seasonal prices, all from the same validated subtotal. Which pattern, and where does the choice live? Strategy: the calculation varies behind one contract. Keep the selector in one place, so eligibility, dates and stacking rules can be audited, instead of the same if in several controllers.

    2. A shipped order must not be cancelled through the path for unpaid orders. What must the model enforce? Legal transitions that depend on the state. A rejected Cancel leaves the order Shipped. A public setter for the status would let callers bypass the rule.

    3. A service checks price <= subtotal before rounding. Both are 1.006, and it publishes 1.01. What contract decision is missing? The currency scale and the final check. Reject inputs with more than two decimals, or define the rounded baseline explicitly, and check the published value. State the midpoint rule and test 1.006 and 0.005.

    4. Pay and Cancel both load a Pending order, and both save successfully. Do State classes fix the race? No. State classes organize behavior; they do not isolate database writes. Save with an expected version (optimistic concurrency) or a conditional update, so only one of the conflicting transitions succeeds; the other rereads and applies the rule again. Make payment side effects idempotent.

    5. An enum with four stable values and one central transition method: must it become four classes? No. A central method or table enforces the same rule with less code. State objects pay off when state-specific behavior is large or switch statements on the state spread through the code.

    6. An outbox commits the event with the order change, and a consumer processes the event twice. What guarantee is still needed? Duplicate-safe handling. The outbox makes the intent to publish durable; it does not make delivery exactly once. Record each processed event ID in the same transaction as its effect, with a unique key so two consumers cannot both claim it, or make the effect itself idempotent.

    Common mistakes

    • Naming a pattern before stating the rule it protects.
    • Spreading policy selection across controllers: choose in one place.
    • A public setter for the status: every transition must go through the rule.
    • Checking an invariant on a value before rounding it, then publishing the rounded value.
    • Expecting State classes to prevent two concurrent saves from both succeeding.
    • Treating an outbox as exactly-once delivery: consumers must handle duplicates.
    • Four classes for four simple states, where a table would do.

    In an interview

    What is the difference between Strategy and State? Strategy swaps one interchangeable algorithm or behavior for another behind one contract, often chosen at run time; a pricing rule is one example. State changes what an object may do as it moves through its lifecycle; the object itself moves between states.

    When is a pattern too much? When a function, a dictionary or a short switch expresses the rule clearly. Patterns earn their place when the variants grow, carry their own data, or change independently.

    How do you stop two requests from both changing the same order? Optimistic concurrency: save with the version you read, and let the database reject a stale write. The losing request rereads the order and decides again.

    How do you test a state machine? Test every allowed transition and every rejected one, and check that a rejection leaves the state as it was.

    What does an outbox guarantee? That the event is stored in the same transaction as the change, so it is never lost. Delivery can still repeat, so consumers must be idempotent.

    Check yourself

    A checkout chooses between standard, loyalty and seasonal prices for the same subtotal. Which pattern fits best?

    A State
    B Strategy
    C Singleton
    D Observer
    Show answer

    Correct answer: B

    The calculation varies behind one contract, and the variant is chosen from outside.

    Option A: State fits behavior that depends on a lifecycle position, not a choice of calculation.

    Option C: A single instance says nothing about choosing a pricing rule.

    Option D: Observer notifies subscribers of events; it does not choose a calculation.

    Two requests load the same Pending order. One pays, one cancels, and both save. What prevents both saves from succeeding?

    A Moving the rules into State classes
    B A version check on the save
    C Making the status setter private
    D Adding a Strategy for each command
    Show answer

    Correct answer: B

    Optimistic concurrency rejects the second save because the order changed after it was read.

    Option A: State classes check legal moves in memory; they do not serialize database writes.

    Option C: A private setter protects the rule inside one process, not between two requests.

    Option D: A strategy organizes calculations; it does not detect conflicting saves.

    A consumer receives the same outbox event twice. What should it do?

    A Process it twice
    B Detect the duplicate and skip it
    C Delete the outbox
    D Retry until it fails
    Show answer

    Correct answer: B

    An outbox can deliver an event more than once, so the consumer records the event ID in the same transaction as its effect, or makes the effect idempotent.

    Option A: Processing twice can charge or ship twice.

    Option C: The outbox is what keeps events from being lost.

    Option D: Retrying does not remove the duplicate.

    Sources

    For the patterns themselves, see the Design Patterns in C# course.

    TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·