Register to get access to free programming courses with interactive exercises

Command–query separation JS: Functions

Command-query Separation (CQS) is a programming principle invented by Bertrand Meyer, creator of the Eiffel language. According to this principle, each function is either a command that performs an action or a query that retrieves data, but not both. Commands are always related to the side effects, and pure functions are only possible for queries.

Team

// Returns true or false
save(user);

According to the CQS principle, the save() function is a command. The only thing it can do is indicate (again, according to the principle) the success of its execution, that is, return true or false (or undefined, as in the case of console.log()). The return of any meaningful data by this function is considered a violation of CQS. However, sometimes it may be impossible to comply with this principle. For example, opening a file for writing returns a file descriptor, a required identifier to work with the file.

const file = fopen('/etc/hosts', 'r');

The separation of commands from queries is closely related to the ideas described in the lesson about pure functions. Commands by definition execute nondeterministic code with side effects. It's non-deterministic because calling the command again either causes an error or causes the action to be repeated (they can be made deterministic but usually have hidden unexpected logical errors). Consequently, separating the query (data return) from the command into a separate function helps to isolate clean code from the code with effects.

Request

// Returns true or false
isAdmin(user);

The isAdmin() function is a predicate, a typical query or, one might even say, a question that sounds like "Is the user an administrator?" Such a function, from the point of view of CQS, cannot change the state of the system: for example, to change the check date to the administrator within the user or even to make the user an administrator. This not only contradicts the CQS, but also common sense. Unlike the previous example, true and false in the case of predicates don't refer to whether the function was executed successfully but rather are the answer to the question asked.

Take a look at an example of a function that changes the raw data:

const users = [
  { 'name': 'Stan', 'children': ['John', 'Mary'] },
  { 'name': 'Donald', 'children': ['James'] },
  { 'name': 'Lily', 'children': [] },
];

// takeChildren() returns an array of children of all users
takeChildren(users); // ['John', 'Mary', 'James']
// It actually changes the users array internally and returns it externally
console.log(users); // => ['John', 'Mary', 'James']

If you make another call to takeChildren(users), the code will most likely fail because the structure of the original array has changed. This behavior of the query function is unnatural. CQS has an alternative wording that perfectly describes the code above: "Asking the question, don't change the answer.

Queries include any calculations:

// The Math.max() function returns the maximum number of the passed
const getMaxNumber = Math.max(1, 30, 4); // 30

This code does not create any side effects and is deterministic. You can call it as many times as you want without risking an error or a wrong result.

Not making changes to requests is a very important principle that must always be followed. Even on an intuitive level, no one would expect that checking isAdmin() or calculating the maximum number in an array could perform any destructive action. On the other hand, in practice such a code is sometimes found, and now you know how to correctly fix it.

The logic of this function is as follows:

// check if there is a name
let username = getName();
if (!username) {
  // If there is no name, we generate and remember
  username = generateName();
  setName(username);
}

If you remove this logic inside the function, what should it be called? Look at this option:

const username = getUserName();

Such a function name is misleading. It looks like a request, but it is not. Without knowing the structure of this function, it is impossible to guess what is going on inside. The first thought will always be that it is just reading some data already written.

The correct approach in these situations is to name the function as a command. Then it will have no hidden meanings. Yes, it will still violate CQS, but we're not trying to hide it. The main thing is clearly shown intention:

const username = setUserName();

// Or even like this
const username = setUserNameIfEmpty();

Recommended materials

  1. Command-query Separation
  2. Principle of least astonishment

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

About Hexlet learning process

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs
profession
Development of front-end components for web applications
10 months
from scratch
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.