Command–Query Separation
CQS · principio de Meyer
Escrito por Darjus Kazakevic · revisado el
Asking a question should not change the answer.
Bertrand Meyer stated the rule in 1988. Every method is either a command, which changes state, or a query, which returns a value. A method should not be both.
The benefit is trust. You can call a query twice, put it in a log line, or watch it in a debugger, and nothing changes. A method like inbox.unread() that also marks the messages as read breaks that trust. A few idioms, such as stack.pop(), mix the two on purpose, and they should stay exceptions you choose.
En esencia — A method either changes state and returns nothing, or returns data and changes nothing. Never both, so a query is always safe to call, cache or reorder.
Cuándo recurrir a él
Recurre a él cuando
- By default, for every method you write
- Getters, and anything named like a question
- Code you want to test, cache or read one line at a time
Reconsidéralo cuando
- Known idioms such as iterator.next(), stack.pop() and queue.poll()
- Atomic read-and-write such as compareAndSet or getAndIncrement
- Fluent builders that change state and return this to chain calls
The two kinds of method
- Command
- A method you call for its effect. It changes state and returns nothing, or at most an id or a status. It is named with a verb: save, cancel, withdraw.
- Query
- A method you call for its answer. It returns a value and leaves the object as it was, so asking twice gives the same answer. It is safe to repeat, cache and reorder.
- The hybrid to avoid
- A method that returns a value and also changes state. The answer depends on how many times you asked, so you cannot cache it, log it or move it safely.
- Accepted exceptions
- Some operations must read and write in one step. Atomic counters, compare-and-set, iterators and queue polling return a value and change state on purpose.
Reglas de diseño
- Make the return type tell the truth
- A command returns void, or at most an id or a status. A query returns data and writes nothing. A reader then knows from the signature alone whether a call changes state.
- Keep getters free of side effects
- No visible writes in a getter: no counters, no cursors, no opened connections. Log lines, assertions and debuggers call getters, and each hidden write runs again.
- Keep atomic operations atomic
- Do not split getAndIncrement() into increment() plus current() if two threads can run between the calls. That creates a race. An atomic read-and-write is a named exception.
Errores habituales
- Getters that write: incrementing a counter, moving a cursor, opening a connection.
- Commands that return rich data "for convenience", so callers start to depend on it.
- Treating the rule as absolute and fighting idiomatic pop() and next() APIs.
- Splitting an atomic operation into advance() plus current(), which creates a check-then-act race.