Command and Query Responsibility Segregation

Command and Query Responsibility Segregation (CQRS) is a great software pattern to discuss in more detail as it is conceptually simple and relatively easy to implement but has dramatic implications to both the application and the developers involved. The pattern clearly separates the commands that affect the state of the application from queries that only retrieve data. Simply put, commands such as updates, adds, and deletes are provided in different services from the queries that do not change any data. 

You might say CQRS again! and we recognize that we have used an example of CQRS in OOP and database design. The same principle does apply to many areas of software development. We are presenting CQRS in this section as a pattern for service design as it leads to some interesting benefits and fits well in modern patterns such as microservices and reactive application design.

CQRS is based on the object-oriented design presented in the late 1980s by Bertrand Meyer's book, Object-Oriented Software Constructionhttp://se.ethz.ch/~meyer/publications/.

If we revisit Chapter 5: Implementing Design Patterns - .NET Corewe illustrated this pattern by splitting our inventory context into two interfaces: IInventoryReadContext and IInventoryWriteContext. As a reminder, here are the interfaces:

public interface IInventoryContext : IInventoryReadContext, IInventoryWriteContext { }

public interface IInventoryReadContext
{
Book[] GetBooks();
}

public interface IInventoryWriteContext
{
bool AddBook(string name);
bool UpdateQuantity(string name, int quantity);
}

As we can see, the GetBooks method is separated from the two methods, AddBook and UpdateQuantity, that modify the state of the inventory. This illustrated CQRS within the code solution.

The same approach can be applied at a service level. If we use a service for maintaining inventory as an example, we would break the service between a service for updating the inventory and another service for retrieving the inventory. This is illustrates in the following diagram:

Let's explore CQRS first by looking at the challenges of when it is applied in cloud-based solutions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.193.129