Beginner LevelSoftware Engineering Principles
What is Command Query Separation (CQS) at the method level?
❓ Interview Prompt: Explain Command Query Separation (CQS), Commands (mutate state, return void) vs Queries (return data, zero side-effects), and predictable API design.
Command Query Separation (CQS) is a software design principle stating that every method should either be a Command or a Query:
•
Command: Executes an action that mutates system state. Returns 'void' (no data).
•
Query: Computes and returns data. Must NOT mutate system state (side-effect free).
•
Rule: Asking a question (Query) should not change the answer!
Code Implementation Example
typescript
class UserAccount {
private balance = 100;
// ✅ Query: Returns balance without side-effects
getBalance(): number { return this.balance; }
// ✅ Command: Mutates state, returns void
withdraw(amount: number): void {
this.balance -= amount;
}
}💡Enforcing Command Query Separation at the object method level.
🎯 Interview Key Takeaway
Separate methods into Commands (state mutation) and Queries (data retrieval) to eliminate unexpected side-effects.
#CQS#Method Design#Principles#Beginner
Back to all Software Engineering Principles Questions→