Functions – Command Query Separation

The idea of Command Query Separation is simple. You should have functions that perform actions that change the state of your system, and you should have functions that return (query) the current state of some part of the system, but your functions shouldn’t do both.  That means you should have Commands and Queries, but should try to avoid Commands that are also queries

Commands

These are the functions that Change the state of your system. They should not have a return value since they asking the system to do something.

void LoginUser(string username,string password);

Commands usually require you to be more careful, since calling them in the wrong order, or at the wrong time can result in an error.

Queries

Queries are the functions that you call when you need to know the state/value of something in your system.

User GetUser(string username);

Queries are functions that you should be able to call at any moment without any fear of them altering the state of your system or having side effects.

 

Trying to write your functions according to the principle of Command Query separation should allow your code to be understood more easily. Seeing a functions without a return value means that it is a command and should be called knowing that it will cause a status change, while a function with a return value will not.

 

There is also an article by Martin Fowler that gives a very simple and clear explanation if you want to learn some more.

Leave a Reply