Neudesic Blogs

Passion for Innovation

The Command Query Separation Principle

A fundamental pattern in Eiffel is the principle of Command Query Separation (also known as CQS). The idea behind CQS is that you separate class operations into two categories:

  • Commands that mutate state on an instance of the class
  • Queries that expose information about the instance

Commands and queries are different; although a successful command will usually alter the state of the targeted object, a query has no side-effects.

Although it’s a bedrock feature in Eiffel, there is no reason why it can’t be used in many languages, such as C#, and queries can be expressed in C# with a read-only property, such as:

public class Account
{
    /// <summary>
    /// What is the current balance?
    /// </summary>
    /// <value>The balance.</value>
    public decimal Balance { get; }
}

Note that a query is typically commented as a question (in my code, anyway). In those cases where an instance must be able to change state via the property you can declare the setter with more restrictive access:

public class Account
{
    /// <summary>
    /// What is the current balance?
    /// </summary>
    /// <value>The balance.</value>
    public decimal Balance { get; private set; }
}

The advantage of CQS is that queries can be executed without side-effects – multiple queries can be executed without any concern for mutating the object state; and query results can be cached (at least between command invocations.) By providing a clear separation between the operations that do (and do not) impact object state, other advanced patterns such as Design by Contract are enabled.

Posted: Jul 29 2010, 07:18 by mickey.williams | Comments (0) RSS comment feed

Tags:
Categories: Custom Application Development | Neudesic Main

Tags

Categories

Archive

Blogroll

Neudesic Social Media

Follow Neudesic on Twitter Follow Neudesic on Facebook Neudesic Neudesic