Pragmatic Objects
  • Pragmatic Objects
  • What's an Object ?
  • Thinking Object
  • Practices
    • The Pragmatic Practices
    • No Getters & Setters
    • Inherit Wisely
    • Wrap Null
    • Wrap Primitives
    • Wrap Collections
    • Expose Snapshots
    • Abandon Composed Names
    • Don't Check Types
    • Minimize Knowledge
    • Immutability
    • Separate Commands & Queries
    • Abandon Statics
    • Invert Dependencies
  • Patterns
    • Domain Model
    • Always Valid
    • Wrapper
    • Command
    • Procedural Object
    • Compute Object
    • Snapshot
    • Value Object
    • Observability
  • Examples
    • Celsiuses / Fahrenheits
Powered by GitBook
On this page
  1. Practices

Separate Commands & Queries

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

PreviousImmutabilityNextAbandon Statics

Last updated 10 months ago

Have you heard of the 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.

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.

Command/Query Separation (CQS)
principle of least astonishment