Command Query Separation
Command Query Separation (CQS)
Command Query Separation (CQS) is a principle that helps in structuring applications by separating operations that change state (commands) from those that only retrieve data (queries).
Commands
Commands modify the system state and involve:
- Validate Parameters – Ensuring inputs meet expected criteria.
- Read from Database – Sometimes necessary for pre-checks.
- Perform Action – Executing business logic.
- Write to Database – Persisting changes.
- Log Event – Tracking changes or actions.
- Update View – Reflecting changes in the UI or API response.
Queries
Queries do not modify the state and involve:
- Validate Parameters – Ensuring inputs are correct.
- Read from Database – Retrieving required data.
- Update View – Presenting the data.
Validation
Validation applies to both commands and queries:
- Check Values – Ensuring correctness (e.g., required fields, format).
- Check Service and Persistence Constraints – Ensuring integrity across business rules and database constraints.
Event Handling
Events help with decoupling components:
- Communication Between Components or Endpoints – Examples include WebSockets, message queues, or APIs exchanging XML/JSON payloads.