Video in progress
What is the Command-Query Separation (CQS) principle, and what bugs come from violating it?
A method either changes state (a command, void) or returns data (a query, without side effects), never both. A query should be safe to call again and again; a "getter" that makes a hidden change gives unexpected results in logs, in the debugger or on a second call.
📖 Answer
A typical CQS violation:
public Coupon getActiveCoupon(Long userId) {
Coupon c = coupons.findActive(userId);
c.markUsed(); // named "get", but it uses up the coupon
return c;
}
Someone calls this just to display it in the UI, and the coupon is burned. Even if you "evaluate" it in the debugger, the state changes. The same if Jackson calls the getter during serialization.
The separated version:
public Optional<Coupon> findActiveCoupon(Long userId) { ... } // query
public void redeem(CouponId id) { ... } // command
Now reading is safe, and the change is visible from the name.
There are exceptions, and they are normal: Iterator.next(), Queue.poll() and AtomicInteger.incrementAndGet() both change state and return a value, because for atomicity both have to be one operation. save() in a repository also returns the saved object. So CQS is not a strict law, but the rule that methods starting with "get", "find" or "is" should not change state is almost always right.
Don't confuse CQRS with CQS: CQRS is this idea at the architecture level (separate read and write models).
Sign up to mark studied questions and save your progress.