Command–query separation
   HOME

TheInfoList



OR:

Command-query separation (CQS) is a principle of imperative
computer programming Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
. It was devised by
Bertrand Meyer Bertrand Meyer (; ; born 21 November 1950) is a French academic, author, and consultant in the field of computer languages. He created the Eiffel programming language and the concept of design by contract. Education and academic career Meyer ...
as part of his pioneering work on the Eiffel programming language. It states that every
method Method (, methodos, from μετά/meta "in pursuit or quest of" + ὁδός/hodos "a method, system; a way or manner" of doing, saying, etc.), literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In re ...
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 effect In medicine, a side effect is an effect of the use of a medicinal drug or other treatment, usually adverse but sometimes beneficial, that is unintended. Herbal and traditional medicines also have side effects. A drug or procedure usually use ...
s.


Connection with design by contract

Command-query separation is particularly well suited to a
design by contract Design by contract (DbC), also known as contract programming, programming by contract and design-by-contract programming, is an approach for designing software. It prescribes that software designers should define formal, precise and verifiable ...
(DbC) methodology, in which the design of a program is expressed as
assert Assertion or assert may refer to: Computing * Assertion (software development), a computer programming technique * assert.h, a header file in the standard library of the C programming language * Assertion definition language, a specification lan ...
ions embedded in the
source code In computing, source code, or simply code or source, is a plain text computer program written in a programming language. A programmer writes the human readable source code to control the behavior of a computer. Since a computer, at base, only ...
, describing the
state State most commonly refers to: * State (polity), a centralized political organization that regulates law and society within a territory **Sovereign state, a sovereign polity in international law, commonly referred to as a country **Nation state, a ...
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
heisenbug In computer programming jargon, a heisenbug is a software bug that seems to disappear or alter its behavior when one attempts to study it. The term is a pun on the name of Werner Heisenberg, the physicist who first asserted the observer effect ...
s.


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 Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impleme ...
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 In computer programming, create, read, update, and delete (CRUD) are the four basic operations (actions) of persistent storage. CRUD is also sometimes used to describe user interface conventions that facilitate viewing, searching, and changing info ...
, 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 Event-driven architecture (EDA) is a software architecture paradigm concerning the production and detection of events. Event-driven architectures are evolutionary in nature and provide a high degree of fault tolerance, performance, and scalabi ...
. * 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 Domain-driven design (DDD) is a major software design approach, focusing on modeling software to match a domain according to input from that domain's experts. DDD is against the idea of having a single unified model; instead it divides a large s ...
.


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: private int x; public int incrementAndReturnX() 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: private int x; public int value() void increment() 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 Stack may refer to: Places * Stack Island, an island game reserve in Bass Strait, south-eastern Australia, in Tasmania’s Hunter Island Group * Blue Stack Mountains, in Co. Donegal, Ireland People * Stack (surname) (including a list of people ...
as an example.


See also

*
Idempotence Idempotence (, ) is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application. The concept of idempotence arises in a number of pl ...
*
Domain-driven design Domain-driven design (DDD) is a major software design approach, focusing on modeling software to match a domain according to input from that domain's experts. DDD is against the idea of having a single unified model; instead it divides a large s ...
*
Create, read, update and delete In computer programming, create, read, update, and delete (CRUD) are the four basic operations (actions) of persistent storage. CRUD is also sometimes used to describe user interface conventions that facilitate viewing, searching, and changing info ...
(CRUD)


References


Further reading

*


External links


Explanation on Martin Fowler's Bliki
{{DEFAULTSORT:Command-query separation Programming principles Object-oriented programming