Course contentsShow
← Software Engineering
Lesson 175 of 1,9335. Software Design PrinciplesFree lesson

Command-Query Separation

Discover why methods should either change state or return data, but not both, for clearer and safer code.

Command-Query Separation

You'll learn why separating methods that change state from those that return information leads to more predictable, maintainable code.

What Is Command-Query Separation?

Command-Query Separation (CQS) is a design principle that states: a method should either do something or answer a question, but not both.

  • Commands change the state of your system but return nothing (or return void)
  • Queries return information but don't modify anything

Think of it like a vending machine and an information booth. The vending machine (command) dispenses a snack and changes its internal inventory, but doesn't tell you facts. The information booth (query) answers your questions but doesn't change anything in the world. You wouldn't expect the information booth to rearrange the city while giving you directions!

Why Does This Matter?

When methods mix commands and queries, code becomes unpredictable. Imagine a method called getNextCustomer() that also removes that customer from the queue. Every time you innocently ask "who's next?" you're accidentally changing the system. Debugging becomes a nightmare because simply looking at data has side effects.

With CQS:

  • Queries are safe — you can call them repeatedly in debugging, logging, or testing without fear
  • Commands are obvious — when you see one, you know state is changing
  • Reasoning becomes easier — you know exactly what a method will or won't do

Example in Plain English

❌ Bad: user.getAndResetLoginAttempts() — asking a question and changing state
✅ Good: user.getLoginAttempts() (query) and user.resetLoginAttempts() (command) — two separate, clear methods

Key Takeaway: Keep methods focused—commands change things, queries answer questions. Don't mix the two, and your code becomes safer and more understandable.