Programming Metaprinciples — CQS: Command Query Separation

Bugra Sitemkar
1 min readJan 4, 2021
Photo by Abbas Tehrani on Unsplash

Every method should only be a command that performs an action or be a query that returns data. In other words, asking a question should not change the answer.

A method should only call a command or should only query some data and return the result.

An example

//Violation
public bool LogIn(string username, string password)

The method performs an action and returns some data. We can not infer what is the returned boolean means by looking at the signature. It might mean if the user is logged in or not but we can not be sure.

//CQS Principle applied
public void LogIn(string username, string password)
public bool IsUserLoggedIn(string username)
public bool IsUserLockedOut(string username)
..

Exceptions

The most common exception for CQS principle is popping a stack. Popping a stack means taking the topmost element from a stack and returning to the caller.

Further Reading

--

--

Bugra Sitemkar

Software Engineer | .NET Enthusiast | Writer. Diving deep into software craftsmanship. 🚀