HOME

TheInfoList



OR:

Command-query separation (CQS) is a principle of imperative
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as anal ...
. 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 idea of design by contract. Education and academic career Meyer rece ...
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 effect In medicine, a side effect is an effect, whether therapeutic or adverse, that is secondary to the one intended; although the term is predominantly employed to describe adverse effects, it can also apply to beneficial, but unintended, consequence ...
s.


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
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, is any collection of code, with or without comment (computer programming), comments, written using a human-readable programming language, usually as plain text. The source code of a Computer program, p ...
, describing the
state State may refer to: Arts, entertainment, and media Literature * ''State Magazine'', a monthly magazine published by the U.S. Department of State * ''The State'' (newspaper), a daily newspaper in Columbia, South Carolina, United States * '' Our ...
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", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
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 message-driven and event-driven architectures: it applies the CQS principle by using separate ''Query'' and ''Command'' messages 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 Event-driven architecture (EDA) is a software architecture paradigm promoting the production, detection, consumption of, and reaction to events. Overview An ''event'' can be defined as "a significant change in state". For example, when a consumer ...
. * 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. Under domain-driven design, the structure and language of software code (class names, ...
.


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 pla ...
*
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. Under domain-driven design, the structure and language of software code (class names, ...


References


Further reading

*


External links


Explanation on Martin Fowler's BlikiCQRS Journey by Microsoft patterns & practicesDDD/CQRS/Event Sourcing List

The CQRS Frequently Asked Questions
{{DEFAULTSORT:Command-query separation Programming principles Object-oriented programming