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.
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:
Task CancelOrderAsync); a query returns data and changes nothing (Task<Order?> GetOrderAsync).CalculateRefund(order, now) with now coming from an injected TimeProvider (in UTC) instead of DateTime.Now inside.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.
"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
GetCustomerthat also updatesLastLoginAtand callsSaveChanges, 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
GetCustomerandRecordLoginbecome 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 readingDateTime.Now, which makes it deterministic and trivially testable. In .NET 8 and later I injectTimeProviderat the edge and pass values inward. And I return records andIReadOnlyList<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.TryDequeueandInterlocked.Incrementreturn 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."
| 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 |
| 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.
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.
Checks the candidate can spot effects that callers don't expect, knows CQS and purity as tools, and applies them pragmatically.
Green flags
Red flags
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.
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.
A pure function has no side effects and depends only on its parameters. Benefits:
Assert.Equal(9.0m, Discount(order, tuesday)).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.
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.
DateTime.Now; inject TimeProvider and test it with FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing.await, .Result or SaveChanges.record with init properties and fix the compile errors; each one was a mutation site.CalculateRefund(Order, DateOnly today) and test 10 cases with [Theory] without any mocks.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)));
}
}
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.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._ = 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.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..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.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.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 |
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.
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.
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].
Last updated 23 Nov 2026.