ArticleslgStudy

science

Command–query separation

Command–query separation is a science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Command–query separation rather than just read about it. In short: Command–query separation (CQS) is a principle of imperative computer programming. It was devised by Bertrand Meyer as part of his pioneering work on the Eiffel programming language.

Key takeaways

  • Command–query separation belongs to science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Command–query separation to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Command–query separation from memory before moving on to harder problems.

Reference excerpt

Command–query separation (CQS) is a principle of imperative computer programming. It was devised by Bertrand Meyer as part of his pioneering work on the Eiffel programming language. It states that every method should either be a command that performs an action, or a query that returns data to the caller, but not both. In other words, asking a question should not change the answer. More formally, methods should return a value only if they are referentially transparent and hence possess no side effects.

Connection with design by contract Command–query separation is particularly well suited to a design by contract (DbC) methodology, in which the design of a program is expressed as assertions embedded in the source code, describing the state of the program at certain critical times. In DbC, assertions are considered design annotations—not program logic—and as such, their execution should not affect the program state. CQS is beneficial to DbC because any value-returning method (any query) can be called by any assertion without fear of modifying program state. In theoretical terms, this establishes a measure of sanity, whereby one can reason about a program's state without simultaneously modifying that state. In practical terms, CQS allows all assertion checks to be bypassed in a working system to improve its performance without inadvertently modifying its behaviour. CQS may also prevent the occurrence of certain kinds of heisenbugs.

Broader impact on software engineering Even beyond the connection with design by contract, CQS is considered by its adherents to have a simplifying effect on a program, making its states (via queries) and state changes (via commands) more comprehensible. CQS is well-suited to the object-oriented methodology, but can also be applied outside of object-oriented programming. Since the separation of side effects and return values is not inherently object-oriented, CQS can be profitably applied to any programming paradigm that requires reasoning about side effects.

Command Query Responsibility Segregation Command query responsibility segregation (CQRS) generalises CQS to services, at the architectures level: it applies the CQS principle by using separate Query and Command interfaces and usually data models to retrieve and modify data, respectively.

Other architectural patterns As we move away from a single representation that we interact with via CRUD, we can easily move to a task-based UI. CQRS fits well with event-based programming models. It's common to see a CQRS system split into separate services communicating with Event Collaboration. This allows these services to easily take advantage of Event Driven Architecture. Having separate models raises questions about how hard it is to keep those models consistent, which raises the likelihood of using eventual consistency. For many domains, much of the logic required is needed when you're updating, so it may make sense to use Eager Read Derivation to simplify your query-side models. If the write model generates events for all updates, you can structure read models as Event Posters, allowing them to be Memory Images and thus avoiding a lot of database interactions. CQRS is suited to complex domains, the kind that also benefits from Domain-Driven Design.

Limitations CQS can introduce complexities for implementing reentrant and multithreaded software correctly. This usually occurs when a non-thread-safe pattern is used to implement the command-query separation. Here is a simple example that does not follow CQS, but is useful for multi-threaded software because it solves the complexity of locking for all other parts of the program, but by doing so it doesn't follow CQS because the function both mutates state and returns it:

Here is a CQS-compliant version. Note that it is safely usable only in single-threaded applications. In a multithreaded program, there is a race condition in the caller, between where increment() and value() would be called:

Even in single-threaded programs, it is sometimes arguably significantly more convenient to have a method that is a combined query and command. Martin Fowler cites the pop() method of a stack as an example.

See also Idempotence Domain-driven design Create, read, update and delete (CRUD)

References

Further reading Meyer, Bertrand (September 1994) [1988]. Object-oriented Software Construction. Prentice Hall. ISBN 0-13-629049-3.

External links Explanation on Martin Fowler's Bliki

Worked examples

Example 1 — a first encounter with Command–query separation

Start with the simplest possible case. Write down what Command–query separation claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Command–query separation before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Command–query separation ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Command–query separation

In research
Command–query separation appears in science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Command–query separation in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Command–query separation is common in secondary-school and first-year university syllabi. It links to neighbouring topics Object-oriented programming, Programming principles, so understanding it makes those chapters shorter.
In everyday life
Look for Command–query separation outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Command–query separation” →

How to study Command–query separation in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Command–query separation means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Command–query separation out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Command–query separation in simple terms?

Command–query separation (CQS) is a principle of imperative computer programming. It was devised by Bertrand Meyer as part of his pioneering work on the Eiffel programming language.

Why does Command–query separation matter?

Because it connects several science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Command–query separation?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Command–query separation.

Tags

  • Object-oriented programming
  • Programming principles

Keep exploring