Basic Concepts of CQS
CQS divides methods into two types:
- Queries – retrieve data but do not change the state of the object.
- Commands – change the state of the object but do not return anything.
Bad Example (Violation of CQS)
class User {
private balance: number = 100;
getBalanceAndDeduct(amount: number): number {
this.balance -= amount; // Simultaneously changes the state and returns a value
return this.balance;
}
}
Problem: This method both performs a query and changes the state, which violates the CQS principle.
Good Example (Adhering to CQS)
class User {
private balance: number = 100;
getBalance(): number {
return this.balance; // Pure query, does not change anything
}
deductBalance(amount: number): void {
this.balance -= amount; // Command, does not return a value
}
}
Now getBalance() simply returns a value, while deductBalance(amount) performs an action without returning anything.
Why Use CQS?
- Code becomes more predictable – you always know which functions change the state and which do not.
- Testing becomes easier – queries can be tested without side effects.
- Code is easier to understand – it is clear when and what is being changed.
- Efficiency in multi-threaded systems – simplifies conflict management.