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

📚 Interview question

What is a hidden side effect? Explain command-query separation, pure functions and immutability, and show how you would remove a side effect hiding inside a C# method.

Covers what hidden side effects are and why they cause bugs, command-query separation (CQS), pure functions, immutability with records and init-only properties, and pushing side effects to the edges of the code.

Mid-Level Theory Intermediate clean-code code-quality command-query-separation immutability pure-functions side-effects

🎯 Key points

  • Side effect = observable change beyond the return value (state, DB, I/O, messages); hidden when the name doesn't say so
  • Command-query separation (Bertrand Meyer): a command changes state and returns nothing (void/Task); a query returns data and changes nothing
  • Pure function: same input -> same output, no side effects; trivially testable and safe to cache or parallelise
  • Hidden inputs count too: DateTime.Now, Guid.NewGuid, static state; inject TimeProvider through DI (built in since .NET 8) and work in UTC
  • Immutability via records, init-only setters, readonly fields, ImmutableArray/FrozenDictionary stops callers mutating shared state
  • Functional core, imperative shell: pure decisions unit-tested without mocks, I/O at the edges covered by a few integration tests
  • Async hides effects too: fire-and-forget Task.Run, async void and unawaited tasks run effects after the caller thinks it's done
  • Pragmatic exceptions: Stack.Pop, TryDequeue, Interlocked.Increment; name them so the effect is obvious

⏱ 30-second answer

A side effect is any observable change a method makes besides returning a value: writing to a field, the database, a file, a queue. It is hidden when the method's name and signature don't tell you, like a GetCustomer that also updates LastSeenAt.

Three tools keep effects visible:

  • Command-query separation: a command changes state and returns nothing (Task CancelOrderAsync); a query returns data and changes nothing (Task<Order?> GetOrderAsync).
  • Pure functions: output depends only on input, so CalculateRefund(order, now) with now coming from an injected TimeProvider (in UTC) instead of DateTime.Now inside.
  • Immutability: records, init setters and immutable collections so callers can't change your state behind your back.

The trade-off: some APIs legitimately combine both (Stack.Pop, TryDequeue, Interlocked.Increment) because atomicity matters, so the rule is make effects obvious, not ban them.

🗣 Full answer (senior)

How I would answer this in an interview

"A side effect is anything a method changes in the world apart from its return value: a field, the database, a file, a message on a queue, even the system clock as an input. Side effects themselves are fine, that's how software does useful work. The problem is hidden ones: a method called GetCustomer that also updates LastLoginAt and calls SaveChanges, or a property getter that lazily calls an API. Callers assume a query is safe to call twice, to cache, or to call from a debugger watch window, and suddenly it isn't.

The tools I use are command-query separation, pure functions and immutability. CQS says a method either changes state and returns nothing, or returns data and changes nothing. So GetCustomer and RecordLogin become two methods and the caller decides. For business rules I aim for pure functions: CalculateDiscount(order, today) takes the date as a parameter rather than reading DateTime.Now, which makes it deterministic and trivially testable. In .NET 8 and later I inject TimeProvider at the edge and pass values inward. And I return records and IReadOnlyList<T> so callers can't mutate an order's lines behind my back.

The mistake I see is being dogmatic about it. Stack.Pop, Queue.TryDequeue and Interlocked.Increment return a value and change state, because doing it atomically matters. The rule isn't 'never combine them', it's 'never surprise the caller'. Pure in the middle, effects at the edges."


Kinds of side effects

Kind Example Usually fine when
State mutation Changing a field or argument The method name says so (AddLine)
I/O DB write, HTTP call, file, queue It is a command at the edge of the system
Hidden input DateTime.Now, Guid.NewGuid(), Random.Shared Injected (TimeProvider) or passed as a parameter
Logging/metrics ILogger, Meter Always acceptable; doesn't change behaviour
Exceptions Throwing Documented failure, not control flow

CQS in practice

Method Kind Return
GetOrderAsync(id) Query Order?
CancelOrderAsync(id) Command Task
IsEligibleForRefund(order) Query, pure bool
TryDequeue(out item) Deliberate exception bool + out

Note: CQS (method-level) is not the same as CQRS (architecture-level separate read and write models). CQRS grew out of CQS but is a much bigger decision.

Production example

A GetBasket endpoint also "refreshed" prices and saved them. When a CDN in front of the API began retrying slow GETs, baskets were re-priced mid-checkout, and [~0.5%] of orders charged a different price from what the customer saw. Splitting it into a pure GetBasket and an explicit RepriceBasket command fixed the discrepancy and made GET safe to cache and retry.

🔍 What the interviewer is checking

Checks the candidate can spot effects that callers don't expect, knows CQS and purity as tools, and applies them pragmatically.

Green flags

  • Gives a concrete hidden-effect example (getter that writes, Get that saves)
  • Treats hidden inputs (clock, randomness) as effects too and mentions TimeProvider
  • Distinguishes CQS from CQRS
  • Names legitimate exceptions like Pop/TryDequeue

Red flags

  • Thinks side effects are bad in general
  • Can't explain why a query with effects is dangerous
  • Uses DateTime.Now in domain logic without concern

📚 Learn in depth

1. What 'observable' means

A function's behaviour is its contract: inputs to outputs. Anything else it reads or writes widens that contract invisibly.

          visible inputs             visible output
  order ──────────────► [ method ] ──────────────► total
                          ▲     │
      hidden inputs ──────┘     └────► hidden outputs
   DateTime.Now, static cache       DB write, field change, email

Every hidden arrow is something a test must set up and something a reader must discover.

2. Command-query separation

Bertrand Meyer formulated CQS for Eiffel: asking a question should not change the answer. It gives you referential transparency for queries: you can call them any number of times, reorder them, cache them, and evaluate them in a debugger safely. HTTP mirrors it: GET should be safe and idempotent, POST is a command.

3. Pure functions

A pure function has no side effects and depends only on its parameters. Benefits:

  • Testable without mocks: Assert.Equal(9.0m, Discount(order, tuesday)).
  • Safe to parallelise: no shared state, no locks.
  • Cacheable/memoisable.
  • Easy to reason about: substitute the call with its result.

4. Immutability in C#

  • record and record struct give value equality and with expressions for non-destructive changes.
  • init accessors allow object initialisers but no later mutation.
  • readonly fields and readonly struct stop mutation after construction.
  • IReadOnlyList<T> is a read-only view; ImmutableArray<T> / FrozenDictionary<TKey,TValue> (from .NET 8) are truly immutable.

A read-only view over a List<T> can still change if the owner mutates the list, so expose immutable copies for shared data.

5. Functional core, imperative shell

  HTTP request
      │
  ┌───▼────────── imperative shell ──────────────┐
  │ load order (DB), read clock (TimeProvider)    │
  │      │                                        │
  │  ┌───▼──── functional core (pure) ──────┐     │
  │  │ decide: refund amount, new status     │     │
  │  └───┬───────────────────────────────────┘     │
  │ save (DB), publish event (bus), log           │
  └───────────────────────────────────────────────┘

The core is unit-tested exhaustively; the shell is covered by a few integration tests.

Try it yourself

  1. Find a method that calls DateTime.Now; inject TimeProvider and test it with FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing.
  2. Search your codebase for property getters containing await, .Result or SaveChanges.
  3. Convert a mutable DTO class to a record with init properties and fix the compile errors; each one was a mutation site.
  4. Write a pure CalculateRefund(Order, DateOnly today) and test 10 cases with [Theory] without any mocks.

💻 Code

A refund method that hides a write and a clock read, refactored into a pure decision plus an explicit command.

// Before: a 'query' that changes state and reads the clock.
public decimal GetRefundAmount(Order order)
{
    var days = (DateTime.Now - order.DeliveredAt).TotalDays;   // hidden input
    var amount = days <= 30 ? order.Total : order.Total * 0.5m;
    order.RefundQuoted = true;                                // hidden mutation
    _db.SaveChanges();                                        // hidden I/O
    return amount;
}
// After: pure core, explicit command at the edge.
namespace Shop.Refunds;

public sealed record Order(Guid Id, decimal Total, DateTimeOffset DeliveredAt, bool RefundQuoted = false);

public static class RefundPolicy
{
    private static readonly TimeSpan FullRefundWindow = TimeSpan.FromDays(30);

    // Pure: same inputs, same output, no effects.
    public static decimal CalculateRefund(Order order, DateTimeOffset now) =>
        now - order.DeliveredAt <= FullRefundWindow ? order.Total : order.Total * 0.5m;
}

public sealed class RefundQuoteHandler(IOrderRepository orders, TimeProvider clock)
{
    // Command: name says it records something; returns the quote it recorded.
    public async Task<decimal> QuoteRefundAsync(Guid orderId, CancellationToken ct)
    {
        var order = await orders.GetAsync(orderId, ct)
            ?? throw new KeyNotFoundException($"Order {orderId} not found");

        var amount = RefundPolicy.CalculateRefund(order, clock.GetUtcNow());
        await orders.SaveAsync(order with { RefundQuoted = true }, ct);   // non-destructive update
        return amount;
    }
}

public interface IOrderRepository
{
    Task<Order?> GetAsync(Guid id, CancellationToken ct);
    Task SaveAsync(Order order, CancellationToken ct);
}
// The pure policy needs no mocks to test.
public class RefundPolicyTests
{
    [Fact]
    public void Full_refund_within_30_days()
    {
        var delivered = new DateTimeOffset(2026, 11, 1, 0, 0, 0, TimeSpan.Zero);
        var order = new Order(Guid.NewGuid(), 200m, delivered);
        Assert.Equal(200m, RefundPolicy.CalculateRefund(order, delivered.AddDays(10)));
    }
}

⚠ Common mistakes

  • Mistake: Writing to the database inside a Get... method or property getter. Why it is wrong: callers retry, cache and debug-evaluate queries assuming they are safe. Instead: split into a query and an explicitly named command.
  • Mistake: Reading DateTime.Now, Guid.NewGuid() or static config deep in business logic. Why it is wrong: it's a hidden input that makes behaviour non-deterministic, time-zone dependent and untestable. Instead: inject TimeProvider via DI, use GetUtcNow(), and pass the value inward as a parameter.
  • Mistake: Starting fire-and-forget work (_ = Task.Run(...), async void, an unawaited SendAsync) inside a request handler. Why it is wrong: the effect happens after the method returns, escapes the request's scope (a disposed DbContext), and its exceptions are lost. Instead: await it, or hand it to a BackgroundService/queue explicitly.
  • Mistake: Mutating arguments passed in (order.Lines.Clear() inside a calculator). Why it is wrong: the caller's object changes unexpectedly. Instead: return a new value, or name the method so the mutation is obvious.
  • Mistake: Side effects inside LINQ lambdas (.Select(x => { count++; return x; })). Why it is wrong: deferred execution runs them zero, one or many times. Instead: keep LINQ lambdas pure; use a foreach for effects.
  • Mistake: Exposing List<T> properties from domain objects. Why it is wrong: anyone can add or remove items, bypassing invariants. Instead: expose IReadOnlyList<T> and provide methods like AddLine.
  • Mistake: Confusing CQS with CQRS. Why it is wrong: CQRS is an architectural split of read and write models with real costs. Instead: apply CQS everywhere; adopt CQRS only when the read and write sides genuinely diverge.
  • Mistake: Testing commands and queries the same way. Why it is wrong: mocking everything around a pure rule produces brittle tests. Instead: unit test pure queries/rules with plain inputs, and cover commands with integration tests against a real database (Testcontainers).

🏛 Senior insight: trade-offs

Seniors don't try to eliminate side effects; they concentrate them. The functional-core/imperative-shell split means the code with the most rules has the fewest dependencies, so it gets the cheapest, fastest tests, while I/O lives in thin handlers covered by a few integration tests. It also makes concurrency bugs rarer because the core shares no mutable state.

What .NET gives you: records and with, init, readonly struct, ImmutableArray/FrozenDictionary, and TimeProvider with FakeTimeProvider for tests. Measure the result by how many of your domain tests need mocks: if it's most of them, effects are leaking into the core.

Option When it fits Cost When not to
Strict CQS Domain services, public APIs Occasionally two calls instead of one Atomic operations (TryDequeue, Interlocked)
Pure functions + injected time Business rules, pricing, eligibility Pass extra parameters Thin I/O glue code
Immutable records DTOs, value objects, events, messages Allocation per change Hot paths with large, frequently mutated state
Mutable entities with guarded methods EF Core aggregates Discipline in method naming Shared cross-thread data

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions keeping behaviour inside the object Why: Checks they can apply Tell, Don't Ask alongside CQS
    How to answer

    Tell, Don't Ask means you tell an object what you want done, and the object decides how, using its own data. Instead of a service doing if (order.Status == Pending && !order.IsPaid) order.Status = Cancelled;, you call order.Cancel(), and the order enforces the rule. That keeps invariants in one place, removes duplicated checks across services and moves you from an anaemic model towards a rich one. It applies to behaviour; for reading data to display or report, querying is exactly right.

  2. When: Candidate mentions CQRS Why: Checks they know CQRS is an architecture decision distinct from CQS
    How to answer

    CQRS at the architecture level separates the write model (aggregates enforcing invariants, normalised SQL) from the read model (denormalised, query-shaped data) so the read side can live in a different store and scale on its own. I adopt it in tiers, each only when measurements justify it: first separate command and query handlers on one database; then read-optimised views in the same database; and only then separate read stores (Cosmos DB, Azure AI Search, Redis) fed by projections from outbox events.

    Separate stores make reads eventually consistent, so I design the UX for it: return the new state from the command, use optimistic UI, or read from the write side right after a change. Event sourcing is optional.

    The trade-off: read scalability and simpler queries versus projection plumbing, lag and two models to keep in sync.

🛠 Real-world problems: how you handle them

A GET endpoint that re-priced baskets on retry
Situation
An e-commerce API at [company] serving [N] checkouts a day. `GET /baskets/{id}` called `GetBasket`, which also refreshed prices from the catalogue and saved them.
Signals
Customer complaints that the charged price differed from the displayed price; finance reconciliation flagged [~0.5%] of orders; App Insights showed duplicate GETs for the same basket within [~2] seconds.
Investigation
Traced a complaint through Application Insights end-to-end transactions, saw two GETs with the same basket id (a CDN/gateway retry on slow responses); read `GetBasket` and found the price refresh and `SaveChangesAsync` call.
Resolution
Immediately: disabled the retry on that route at the gateway. Then: split `GetBasket` (pure query, `AsNoTracking`) from an explicit `RepriceBasket` command called at well-defined points, and locked the price at checkout start.
Prevention
Architecture test (NetArchTest) asserting query handlers don't reference `SaveChangesAsync`; review checklist item 'does any Get/query write?'; contract test asserting GET is idempotent.

How to tell it (STAR)

**S:** Our basket API had a GET that quietly re-priced and saved the basket, and [~0.5%] of orders were charged a different price from what customers saw. **T:** I was asked to find out why prices drifted. **A:** In Application Insights I found duplicate GETs from a gateway retry and traced them to the hidden save inside `GetBasket`. I switched off the retry that day, then split the method into a pure query and an explicit reprice command, and added an architecture test so query handlers can't save. **R:** Price mismatches went from [~X per week] to [zero], and GETs became safe to cache, which cut basket latency by [~Y ms].

↩ Usually asked after

More in Clean Code

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me