Techniquecore
Separate query from modifier
Also called split query and command, separate query from command.
Split a function that both returns a value and changes state into a query that only returns the value and a modifier that only makes the change.
- Family
- refactoring
- Intent
- Let a caller ask a question without changing anything.
Purpose
A function that returns a value and also changes state is hard to use safely. A caller who only wants the value must accept the change too. A test that reads the value twice changes the state twice.
Separate query from modifier splits the function in two. The query returns the value and changes nothing. The modifier makes the change and returns nothing. The catalogue card splits getTotalOutstandingAndSendBill into totalOutstanding and sendBill.1
The rule behind the refactoring is command-query separation. Martin Fowler writes that "The term 'command query separation' was coined by Bertrand Meyer in his book “Object Oriented Software Construction“".2 The principle divides methods into two groups. Queries "Return a result and do not change the observable state of the system (are free of side effects)." Commands "Change the state of a system but do not return a value."2
Steps
- Copy the function. Give the copy a name that says what it returns.
- Remove each side effect from the copy, so that it only computes and returns the value.
- Find each caller of the old function. If the caller uses the return value, replace the call with a call to the query, followed by a call to the old function.
- Remove the return value from the old function, and give it a name that says what it changes.
- Test after each step.
- Look for duplication: the modifier can often call the query, or both can call a shared helper.
Example
chargeAndTotal adds the open invoices of a customer, sends a bill and returns the total. A report that only wants the total must send a bill to get it. After the split, totalOutstanding is a query and sendBill is a modifier.
import assert from "node:assert/strict";
const sent = [];
const customer = { name: "Ana", invoices: [{ amount: 40 }, { amount: 2 }] };
function chargeAndTotalBefore(c) {
const total = c.invoices.reduce((sum, each) => sum + each.amount, 0);
sent.push(`bill to ${c.name}: ${total}`);
return total;
}
function totalOutstanding(c) {
return c.invoices.reduce((sum, each) => sum + each.amount, 0);
}
function sendBill(c) {
sent.push(`bill to ${c.name}: ${totalOutstanding(c)}`);
}
assert.equal(chargeAndTotalBefore(customer), 42);
assert.equal(sent.length, 1);
// The query can run any number of times and sends nothing.
assert.equal(totalOutstanding(customer), 42);
assert.equal(totalOutstanding(customer), 42);
assert.equal(sent.length, 1);
// The caller that wants both now makes both calls.
const total = totalOutstanding(customer);
sendBill(customer);
assert.equal(total, 42);
assert.deepEqual(sent, ["bill to Ana: 42", "bill to Ana: 42"]);
console.log("separate query from modifier: tests pass");
separate query from modifier: tests pass
The modifier calls the query, so the sum is written once.
| Language | What the example shows |
|---|---|
| JavaScript | the split into totalOutstanding and sendBill, as above |
| Python | the same split, with the query as a function that does not touch the list of sent bills |
| Go | the same split; the query takes the customer by value, and the modifier takes a pointer to the outbox that it changes |
from dataclasses import dataclass, field
@dataclass
class Customer:
name: str
invoices: list[int] = field(default_factory=list)
sent: list[str] = []
def charge_and_total_before(c: Customer) -> int:
total = sum(c.invoices)
sent.append(f"bill to {c.name}: {total}")
return total
def total_outstanding(c: Customer) -> int:
return sum(c.invoices)
def send_bill(c: Customer) -> None:
sent.append(f"bill to {c.name}: {total_outstanding(c)}")
ana = Customer("Ana", [40, 2])
assert charge_and_total_before(ana) == 42
assert len(sent) == 1
assert total_outstanding(ana) == 42
assert total_outstanding(ana) == 42
assert len(sent) == 1
total = total_outstanding(ana)
send_bill(ana)
assert total == 42
assert sent == ["bill to Ana: 42", "bill to Ana: 42"]
print("separate query from modifier: tests pass")
separate query from modifier: tests pass
package main
import (
"fmt"
"reflect"
)
type Customer struct {
Name string
Invoices []int
}
// totalOutstanding is a query: it reads the customer and changes nothing.
func totalOutstanding(c Customer) int {
total := 0
for _, amount := range c.Invoices {
total += amount
}
return total
}
// sendBill is a modifier: it adds a bill to the outbox and returns nothing.
func sendBill(c Customer, outbox *[]string) {
*outbox = append(*outbox, fmt.Sprintf("bill to %s: %d", c.Name, totalOutstanding(c)))
}
func check(ok bool, what string) {
if !ok {
panic(what)
}
}
func main() {
var outbox []string
ana := Customer{Name: "Ana", Invoices: []int{40, 2}}
check(totalOutstanding(ana) == 42, "query")
check(totalOutstanding(ana) == 42, "query again")
check(len(outbox) == 0, "query sent nothing")
total := totalOutstanding(ana)
sendBill(ana, &outbox)
check(total == 42, "total")
check(reflect.DeepEqual(outbox, []string{"bill to Ana: 42"}), "outbox")
fmt.Println("separate query from modifier: tests pass")
}
separate query from modifier: tests pass
When to use
- A function with a return value and a side effect. A caller cannot get the value without the effect.2
- A value that callers read many times. Fowler writes that "you can use queries in many situations with much more confidence, introducing them anywhere, changing their order. You have to be more careful with modifiers."2
- Before caching or moving the query. A query with no side effects can be cached, inlined or moved without a change in behavior.
Pitfalls
Useful exceptions. Command-query separation is a guideline. Fowler gives the exception himself: "Popping a stack is a good example of a query that modifies state." He adds that he is "prepared to break it to get my pop."2 The same is true of next on an iterator, which he also names.2
Concurrency. When two threads share the state, a query followed by a modifier is two steps, and another thread can change the state between them. An operation such as pop or compare-and-swap is one call because it must be atomic. Do not split it.
Observable state only. A query can still change state that no caller can see, such as a cache. Fowler notes that "the rule about not changing state really only applies to the ObservableState of the system."2
Tools that do it
No IDE has one action for this refactoring. It is a sequence of Extract Function, Change Function Declaration and a removal of the return value. See Extract Function and Change Function Declaration.
The catalogue lists the refactoring in the first edition, the second edition and the Ruby edition of Refactoring, with the tags refactoring-apis and immutability.3 In the second edition it is in Chapter 11, Refactoring APIs.4
References
- Martin Fowler, Catalog of Refactorings, Separate Query from Modifier, the entry, the getTotalOutstandingAndSendBill sketch
- Martin Fowler, CommandQuerySeparation, 5 December 2005, the whole note
- Martin Fowler, Catalog of Refactorings, index, the entry separateQueryFromModifier, its books and tags
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 11, Refactoring APIs, Separate Query from Modifier
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag P2TV52 Edit this page History Report an error Markdown