Command Query Separation (CQS)
Command Query Separation (CQS) principle
CQS divides methods into two types:
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.