Command-Query Separation

*Disclosure: This post may contain affiliate links, meaning, at no cost to you I may get some coffee money if you click through and make a purchase.

I’ve been dropping some short but, hopefully, meaningful posts about subjects within software development like Names and Don’t Repeat Yourself. These appear to be getting some interest so I’m going to look at putting together more short to the point titbits, or tidbits, of recommended software development best practices.

So this week’s titbit is the aim of incorporating the Command-Query Separation principle into our code.

The main goal of Command-Query is that we should aim to write our code in such a way that methods either do something or give us something but that they do NOT do both.

  • Commands: Do something; change the state of the system.
  • Queries: Give us something; give us back a result but do not change the state of the system.

This concept was coined by Bertrand Meyer the author of Object-Oriented Software Construction in the late 1980s and as mentioned above is quite straightforward to understand but not as easy to implement all the time.

Martin Fowler wrote an article in 2005 that provides a good example of where this is the case. If you are using a 3rd party data structure which does not follow this rule and you perform a query on that data structure the state of the system may be changed as a result, thereby breaking the principle. He also continues with this train of thought, we should aim to follow these best practices where we can and when we can but that is not always the case.

My view here is we can either review our implementation, and look to improve it if it’s a break we are causing, or we can accept that these things happen but try to work around the issue so we ensure our code is as clean and expressive as we can make it.

A quote from one of my university lecturers was “Write your code like the person taking it on after you are an axe-wielding murder who knows where you live.”, a bit dramatic but the point is there; we should aim to make our code clean and clear and this kind of decoupling is certainly something we should all be considering.

Leave a Reply

Your email address will not be published. Required fields are marked *