Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Command–query separation
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|IT architecture separating actions and reads}} {{refimprove|date=February 2008}} '''Command-query separation''' ('''CQS''') is a principle of [[Imperative programming|imperative]] [[computer programming]]. It was devised by [[Bertrand Meyer]] as part of his pioneering work on the [[Eiffel (programming language)|Eiffel programming language]]. It states that every [[Method (computer science)|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''.<ref>{{cite web |last=Meyer|first=Bertrand|title=Eiffel: a language for software engineering|url=http://laser.inf.ethz.ch/2012/slides/Meyer/eiffel_laser_2012.pdf|page=22|access-date=16 December 2014}}</ref> More formally, methods should return a value only if they are [[Referential transparency|referentially transparent]] and hence possess no [[Side effect (computer science)|side effect]]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 [[Computer program|program]] is expressed as [[Assertion (software development)|assert]]ions embedded in the [[source code]], describing the [[State (computer science)|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 [[heisenbug]]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.{{citation needed|date=December 2014}} CQS is well-suited to the [[object-oriented programming|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.{{citation needed|date=December 2014}} ==Command Query Responsibility Segregation== [[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.<ref>{{cite web|last=Young|first=Greg|title=CQRS Documents|url=http://cqrs.files.wordpress.com/2010/11/cqrs_documents.pdf|access-date=2012-12-28}}</ref><ref name="FowlerCQRS">{{cite web|last=Fowler|first=Martin|title=CQRS|url=http://martinfowler.com/bliki/CQRS.html|access-date=2011-07-14}}</ref> ==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|Domain-Driven Design]].<ref name="FowlerCQRS" /> ==Limitations== CQS can introduce complexities for implementing [[Reentrant (subroutine)|reentrant]] and [[Multithreading (software)|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: <syntaxhighlight lang="java"> private int x; public int incrementAndReturnX() { lock x; // by some mechanism x = x + 1; int x_copy = x; unlock x; // by some mechanism return x_copy; } </syntaxhighlight> 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 <code>increment()</code> and <code>value()</code> would be called: <syntaxhighlight lang="java"> private int x; public int value() { return x; } void increment() { x = x + 1; } </syntaxhighlight> 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 (software engineer)|Martin Fowler]] cites the <code>pop()</code> method of a [[Stack (abstract data type)|stack]] as an example.<ref>{{cite web|last=Fowler|first=Martin|title=CommandQuerySeparation|url=http://martinfowler.com/bliki/CommandQuerySeparation.html|access-date=5 December 2005}}</ref> ==See also== *[[Idempotence#Computer science meaning|Idempotence]] *[[Domain-driven design]] *[[Create, read, update and delete]] (CRUD) ==References== {{Reflist}} ==Further reading== *{{cite book | first = Bertrand | last = Meyer | author-link = Bertrand Meyer | orig-year = 1988 | date = September 1994 | title = Object-oriented Software Construction | publisher = Prentice Hall | isbn = 0-13-629049-3 }} ==External links== *[http://martinfowler.com/bliki/CommandQuerySeparation.html Explanation on Martin Fowler's Bliki] {{DEFAULTSORT:Command-query separation}} [[Category:Programming principles]] [[Category:Object-oriented programming]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Citation needed
(
edit
)
Template:Cite book
(
edit
)
Template:Cite web
(
edit
)
Template:Refimprove
(
edit
)
Template:Reflist
(
edit
)
Template:Short description
(
edit
)