Skip to content

Command Query Separation

20081124 (2008 November 24 Monday)

Definitions:

  • A command is a feature of a class that changes the state of a object but returns nothing: a procedure.
  • A query is a feature of a class that changes nothing and returns something: a function.
  • A procedure is a routine that is a command.
  • A function is a routine that is a query, or non-writeable attribute.

So why a separation?

  • It makes code simpler and life easier. Yes your code will be cleaner, simpler, more elegant, faster. You may struggle at first. I have had people tell be that in such and such a situation it is not possible. So I had to show them how. It is worth learning, the effort will force you to change your design in a subtle way that will make it better.
  • It reduces use of temporary variables. As now you use object variables; When you have commends that return something you end up having to store the value in a temporary variable until you are ready. With command query separation you keep it in the object until you are ready.
  • It makes Design-Contracts / Code-Contracts possible.

Main objections

But I need to return a state

No you don’t store the state in the this/self/current object. Consider how this state affects post-condition. Consider how this state affects pre-condition of other methods. Write these pre and post-conditions; This will lead you to write an accessor to this new state. The client code can use this accessor.

It stifles creativity

So does goto, yet we avoid goto when ever the language is sufficiently structured to allow it. Command Query Separation will one day be like structured programming, totally ignored as it is built in to the languages and no one notices it.

C++ tip

Make query methods const. i.e.
return_type method_name(args) const {}

Turn on deep const checking. The standard for C++ says to do only shallow const checking. But deep checking is needed (any code written with deep checking, will conform to the shallow checking rules).

Turn on methods whose return type is not void must be const check.

We use PC-lint to do these checks (and other checking)

Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: