Skip to content

Separate Query from Modifier: Split Reads from State Changes

Split a function that both returns a value and changes state into a side-effect-free query and a separate modifier, so callers can read without changing anything.

7 min readRefactoring

Separate Query from Modifier takes one function that does two jobs, answering a question and changing state, and turns it into two. The query returns the value and changes nothing. The modifier changes state and returns nothing, or at most a status. This guide uses Harbor Desk, an invented helpdesk tool. Its TicketQueue has a method that finds the oldest urgent unassigned ticket and assigns it to an agent in the same call. You will split it into findNextUrgent and assign, with tests passing after every step. Interviewers like this refactoring because it tests whether you notice hidden side effects. It also tests whether you know when splitting is wrong, for example when the read and the write must happen atomically.

The problem

A situation where the obvious design starts to hurt.

In Harbor Desk, takeNextUrgent(agent) scans the queue for unassigned tickets with priority 3 or higher, picks the oldest, sets its assignee and returns it. The name hints at the side effect, but callers mostly see a function that returns a ticket.

That causes trouble as soon as someone only wants to look. Suppose a team adds a supervisor dashboard tile showing which urgent ticket is next. The obvious call is takeNextUrgent, and every page refresh silently assigns a ticket to whoever is viewing. Tests that call the method twice get different answers, so you cannot write a simple assertion about what is next without mutating fixtures. Logging or debugging code that calls the method changes the system it is trying to observe.

The root issue is that there is no way to ask the question without paying the side effect.

Before and after

The same code, before and after the change.

Before

type Ticket = {
  id: number;
  priority: number;
  createdAt: number;
  assignee: string | null;
};

class TicketQueue {
  constructor(private tickets: Ticket[]) {}

  takeNextUrgent(agent: string): Ticket | null {
    let best: Ticket | null = null;
    for (const t of this.tickets) {
      if (t.assignee !== null || t.priority < 3) continue;
      if (best === null || t.createdAt < best.createdAt) best = t;
    }
    if (best !== null) best.assignee = agent;
    return best;
  }
}

const queue = new TicketQueue([
  { id: 101, priority: 2, createdAt: 1000, assignee: null },
  { id: 102, priority: 4, createdAt: 1200, assignee: null },
  { id: 103, priority: 5, createdAt: 1100, assignee: null },
]);

const t = queue.takeNextUrgent("maya");
if (t !== null) console.log(`${t.id} ${t.assignee}`); // 103 maya

After

type Ticket = {
  id: number;
  priority: number;
  createdAt: number;
  assignee: string | null;
};

class TicketQueue {
  constructor(private tickets: Ticket[]) {}

  findNextUrgent(): Ticket | null {
    let best: Ticket | null = null;
    for (const t of this.tickets) {
      if (t.assignee !== null || t.priority < 3) continue;
      if (best === null || t.createdAt < best.createdAt) best = t;
    }
    return best;
  }

  assign(ticket: Ticket, agent: string): void {
    ticket.assignee = agent;
  }
}

const queue = new TicketQueue([
  { id: 101, priority: 2, createdAt: 1000, assignee: null },
  { id: 102, priority: 4, createdAt: 1200, assignee: null },
  { id: 103, priority: 5, createdAt: 1100, assignee: null },
]);

const t = queue.findNextUrgent();
if (t !== null) queue.assign(t, "maya");
if (t !== null) console.log(`${t.id} ${t.assignee}`); // 103 maya

Why it's worth it

What the change buys you.

A query you can call any number of times without consequences is easy to reason about. findNextUrgent returns the same ticket on every call until something assigns it, so the dashboard tile, a log line and a test assertion can all use it safely. You can move it, cache it or call it from a debugger without worrying about what it does to the queue.

The modifier becomes explicit at the call site. Reading queue.assign(t, "maya") tells you exactly where state changes, instead of hiding that change inside something that looks like a lookup.

This is the command-query separation principle associated with Bertrand Meyer: a method either answers a question or performs an action, not both. Following it also makes each half simpler to test. The query gets plain input and output tests. The modifier gets a test that checks the state after the call.

The cost is that the caller now makes two calls, and in a concurrent setting the gap between them matters. That trade-off is covered in the cautions.

  • The query can be called freely from dashboards, logs, tests and debuggers without changing state.
  • State changes are visible at the call site instead of hidden inside a lookup.
  • Each method is smaller and has one kind of test: output checks for the query, state checks for the modifier.
  • Callers that only want to look can now do so, which removes a whole category of accidental-assignment bugs.

Careful with

  • Query-then-modify is not atomic. If two agents can claim tickets concurrently, both may find the same ticket before either assigns it. Keep a combined claim operation guarded by a lock, a conditional database update or a transaction when atomicity matters.
  • Some combined operations are idiomatic and expected, such as a stack's pop or an iterator's next. Do not split them just to satisfy the principle.
  • Make sure the query really has no side effects after the split. Hidden writes like updating a last-accessed timestamp or a metrics counter defeat the purpose.
  • Removing assign from callers that only wanted the value changes behaviour. Do it in its own commit with its own tests.

Step by step

Small, safe steps, with the tests passing after each.

  1. Pin the current behaviour with tests: takeNextUrgent returns the oldest unassigned ticket with priority 3 or higher, sets its assignee, and returns null when nothing qualifies.

  2. Copy the method body into a new method findNextUrgent that takes no agent and omits the line that sets the assignee. Nothing calls it yet, so tests still pass.

  3. Add tests for findNextUrgent: it returns the expected ticket, and calling it twice returns the same ticket while leaving every assignee unchanged.

  4. Add assign(ticket, agent), which only sets the assignee. Test it directly.

  5. Rewrite the body of takeNextUrgent to call findNextUrgent, then assign if the result is not null, then return the result. Run the tests; behaviour is unchanged.

  6. Update callers one at a time to call findNextUrgent followed by assign, running tests after each change.

  7. Once no callers remain, delete takeNextUrgent and its now redundant tests.

  8. As a separate, clearly labelled change, find callers that only needed the value, such as a preview, and drop their assign call. That is a deliberate behaviour fix, not part of the refactoring.

Common questions

Short answers to the usual doubts.

Is this the same as command-query separation?

It is the refactoring that moves code towards that principle. Command-query separation says a method should either return information or change state. Separate Query from Modifier is the mechanical process for fixing a method that does both.

Does splitting the method mean the queue gets scanned twice?

Not here. The caller runs the scan once in findNextUrgent and passes the result to assign, which does no scanning. If a modifier you extract would need to recompute the query, pass it the query's result instead of searching again.

When should I keep the combined method?

When the read and the write must happen as one indivisible step, for example claiming a job from a shared queue across several workers. In that case keep a single claim operation backed by a lock or a conditional update, and still offer a separate side-effect-free query for callers who only want to look.

Can the modifier return anything at all?

Returning a status, such as whether the update succeeded or how many rows changed, is a common and reasonable compromise. What you want to avoid is a modifier that also serves as the main way to read domain data.

How would I bring this up in an interview?

When reviewing code, point out any function whose name sounds like a lookup but mutates state, explain the risk of callers triggering it accidentally, and propose the split. Then mention the concurrency caveat. Showing you know when not to split is what separates a strong answer from a textbook one.