CQS는 Command(명령)과 Query(질의)의 역할을 구분하는 설계 원칙입니다.
class Account {
private int balance;
public int withdraw(int amount) {
if (amount > balance) {
throw new IllegalArgumentException("잔액 부족");
}
balance -= amount; // Command
return balance; // Query
}
}
Account 클래스의 withdraw 메서드는 명령과 질의가 혼합되어 있습니다.
balance값을 감소시켜 상태를 변경합니다.balance 값을 반환합니다.public class Account {
private int balance;
// command
public void withdraw(int amount) {
if (amount > balance) {
throw new IllegalArgumentException("잔액 부족");
}
balance -= amount;
}
// query
public int getBalance() {
return balacne;
}
}
withdraw는 상태를 변경하고, getBalance는 상태를 조회합니다. 각 메서드의 역할이 분명하므로 코드의 가독성이 향상됩니다.getBalance를 호출한다고 해서 객체의 상태가 변경될 가능성이 없습니다. 따라서 호출자는 안전하게 상태를 조회할 수 있습니다.withdraw와 getBalance를 개별적으로 테스트할 수 있습니다.