Command-Query Responsibility Segregation (CQRS) Principle
- is Command-Query Separation on a larger scale
- originated with Bertrand Meyer’s Command and Query Separation Principle
- If you have a return value you cannot mutate the state. If you mutate the state your return type must be void
CQRS - Example
class CustomerService {
void makeCustomerPreferred(String customerId);
Customer getCustomer(String customerId);
List<Customer> getCustomersWithName(String name);
List<Customer> getPreferredCustomers();
void changeCustomerLocale(String customerId, Locale locale);
void createCustomer(Customer customer);
void editCustomerDetails(CustomerDetails customerDetails);
}
Applying CQRS on the CustomerService would result in two services as shown below
class CustomerCommandService {
void makeCustomerPreferred(String customerId);
void changeCustomerLocale(String customerId, Locale locale);
void createCustomer(Customer customer);
void editCustomerDetails(CustomerDetails customerDetails);
}
class CustomerQueryService {
Customer getCustomer(String customerId);
List<Customer> getCustomersWithName(String name);
List<Customer> getPreferredCustomers();
}
CQRS - Different Needs
This separation enforces the notion that the Command side and the Query side have very different needs. The architectural properties associated with use cases on each side tend to be quite different. Just to name a few:
|
Consistency |
|
|---|---|
|
Data Storage |
|
|
Scalability |
|