Separate Commands & Queries

Separate your methods such as a method is either a command or a query.

Have you heard of the Command/Query Separation (CQS) principle ?

It states that every method of a class should either change the state of the object or return a value, but not both.

For example, when asking the age of a user should not change the age or update any other information of the user. That would violate the principle of least astonishment.

With a few exceptions concerning caching and lazily computed values.

Similarly, changing the user's age shouldn't return a value. What kind of value should it return ?

The CQS principle naturally forces the program to shape itself into a succession of queries and commands.

You perform commands depending on the result of a query. And when you perform commands, you check the result by performing another query.

There's one exception, though : when the command creates a new object.

Sometimes, you need to get access to that object or to keep a reference.

Think of the ticketing system when you buy a coffee or go to the hospital. You keep this ticket close so you can trade it for your coffee or your consultation.

Sometimes, we need to keep a reference to an object without holding the object itself, such as when performing jobs in a message queue. In this case, it's perfectly fine to perform a command (creating the job) and returning a result (the ID of the job).

But that's probably the only case where a violation of CQS is viable.

Last updated