Tuesday, 5 August 2014

Command Query Responsibility Segregation (CQRS)

Command Query Responsibility Segregation (CQRS)
  • A design pattern that suggests we should separating methods that change state from those that don't. In which way, we can even separate the databases used for Reads and Writes and therefore being able to optimize such databases for Reads and Writes.
  • Two main behaviours of a model is to be updated and displayed. For instance, you store a product in certain way and present it to the UI in another way. 
  • Query Models are to read data from database to be displayed for the presentation.
  • Command Models are to execute Create/Update/Delete commands from the Presentation to the database.
  • Syncing the separate databases with each other would be an overhead and one way to achieve it would be using Replication models (publisher and subscribers)
  • The fundamental idea is that we should divide an object's methods into two separated categories:
    • Queries: Return a result and do not change the observable state of the system (are free of side effects).
    • Commands: Change the state of a system but do not return a value.

You'd refactor and group the methods of the Product repository into separate classes:
  • ProductQuery
  • ProductSaveCommand
  • ProductDeleteCommand
Further reading:
Event Sourcing