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 mayafrom dataclasses import dataclass
from typing import Optional
@dataclass
class Ticket:
id: int
priority: int
created_at: int
assignee: Optional[str] = None
class TicketQueue:
def __init__(self, tickets: list[Ticket]) -> None:
self._tickets = tickets
def take_next_urgent(self, agent: str) -> Optional[Ticket]:
best: Optional[Ticket] = None
for t in self._tickets:
if t.assignee is not None or t.priority < 3:
continue
if best is None or t.created_at < best.created_at:
best = t
if best is not None:
best.assignee = agent
return best
queue = TicketQueue([
Ticket(101, 2, 1000),
Ticket(102, 4, 1200),
Ticket(103, 5, 1100),
])
t = queue.take_next_urgent("maya")
if t is not None:
print(f"{t.id} {t.assignee}") # 103 maya<?php
final class Ticket
{
public function __construct(
public int $id,
public int $priority,
public int $createdAt,
public ?string $assignee = null,
) {}
}
final class TicketQueue
{
/** @param Ticket[] $tickets */
public function __construct(private array $tickets) {}
public function takeNextUrgent(string $agent): ?Ticket
{
$best = null;
foreach ($this->tickets as $t) {
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;
}
}
$queue = new TicketQueue([
new Ticket(101, 2, 1000),
new Ticket(102, 4, 1200),
new Ticket(103, 5, 1100),
]);
$t = $queue->takeNextUrgent('maya');
if ($t !== null) {
echo "{$t->id} {$t->assignee}\n"; // 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 mayafrom dataclasses import dataclass
from typing import Optional
@dataclass
class Ticket:
id: int
priority: int
created_at: int
assignee: Optional[str] = None
class TicketQueue:
def __init__(self, tickets: list[Ticket]) -> None:
self._tickets = tickets
def find_next_urgent(self) -> Optional[Ticket]:
best: Optional[Ticket] = None
for t in self._tickets:
if t.assignee is not None or t.priority < 3:
continue
if best is None or t.created_at < best.created_at:
best = t
return best
def assign(self, ticket: Ticket, agent: str) -> None:
ticket.assignee = agent
queue = TicketQueue([
Ticket(101, 2, 1000),
Ticket(102, 4, 1200),
Ticket(103, 5, 1100),
])
t = queue.find_next_urgent()
if t is not None:
queue.assign(t, "maya")
if t is not None:
print(f"{t.id} {t.assignee}") # 103 maya<?php
final class Ticket
{
public function __construct(
public int $id,
public int $priority,
public int $createdAt,
public ?string $assignee = null,
) {}
}
final class TicketQueue
{
/** @param Ticket[] $tickets */
public function __construct(private array $tickets) {}
public function findNextUrgent(): ?Ticket
{
$best = null;
foreach ($this->tickets as $t) {
if ($t->assignee !== null || $t->priority < 3) {
continue;
}
if ($best === null || $t->createdAt < $best->createdAt) {
$best = $t;
}
}
return $best;
}
public function assign(Ticket $ticket, string $agent): void
{
$ticket->assignee = $agent;
}
}
$queue = new TicketQueue([
new Ticket(101, 2, 1000),
new Ticket(102, 4, 1200),
new Ticket(103, 5, 1100),
]);
$t = $queue->findNextUrgent();
if ($t !== null) {
$queue->assign($t, 'maya');
}
if ($t !== null) {
echo "{$t->id} {$t->assignee}\n"; // 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
popor an iterator'snext. 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
assignfrom 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.
Pin the current behaviour with tests:
takeNextUrgentreturns the oldest unassigned ticket with priority 3 or higher, sets its assignee, and returns null when nothing qualifies.Copy the method body into a new method
findNextUrgentthat takes no agent and omits the line that sets the assignee. Nothing calls it yet, so tests still pass.Add tests for
findNextUrgent: it returns the expected ticket, and calling it twice returns the same ticket while leaving every assignee unchanged.Add
assign(ticket, agent), which only sets the assignee. Test it directly.Rewrite the body of
takeNextUrgentto callfindNextUrgent, thenassignif the result is not null, then return the result. Run the tests; behaviour is unchanged.Update callers one at a time to call
findNextUrgentfollowed byassign, running tests after each change.Once no callers remain, delete
takeNextUrgentand its now redundant tests.As a separate, clearly labelled change, find callers that only needed the value, such as a preview, and drop their
assigncall. 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.