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
(section)
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!
==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>
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)