Command Query Separation
5 December 2005
The term 'command query separation' was coined by Bertrand Meyerin his book “Object Oriented Software Construction“ - a book that isone of the most influential OO books during the early days ofOO. (The first edition is the one that had the influence, the secondedition is good but you'll need several months in a gym before youcan lift it.)
The fundamental idea is that we should divide an object's methodsinto two sharply separated categories:
- Queries: Return a result and do not change theobservable state of thesystem (are free of side effects).
- Commands: Change the state of a system but do notreturn a value.
Because the term 'command' is widely used in other contexts Iprefer to refer to them as'modifiers', you also see the term'mutators'.
The really valuable idea in this principle is that it's extremelyhandy if you can clearly separate methods that change state fromthose that don't. This is because you can use queries in manysituations with much more confidence, introducing them anywhere,changing their order. You have to be more careful with modifiers.
The notion in the principle is that the return type is thegive-away for the difference. It's a good convention because most ofthe time it works well. Consider the java idiom for iterating througha collection: thenext
method both gives the next item inthe collection and advances the iterator. Personally I'd much prefer astyle that has separateadvance
andcurrent
methods.
Meyer likes to use command-query separation absolutely, but thereare exceptions. Popping a stack is a good example of a query thatmodifies state. Meyer correctly says that you can avoid having thismethod, but it is a useful idiom. So I prefer to follow thisprinciple when I can, but I'm prepared to break it to get my pop.
It would be nice if the language itself would support thisnotion. I could imagine a language that would detect state changingmethods, or at least allow the programmer to mark them. One reasonthat languages can't detect them automatically is that the ruleabout not changing state really only applies to theObservableStateof the system. Using programmer markings seems more reasonable butis rare. The only case I've really come across it is the constmodifier in C++. Since I haven't used C++ for many years it's hardfor me to assess how useful it is in practice. My sense is that goodC++ers use const a lot and like it.