Problem of Bloated Domain objects
In business software applications, the domain objects (entities) are used to represent the business domain. As the application grows and adds more business logic, the service layer, mappers and other patterns gets applied. Often this leads to domain object becomes bloated and the related components become huge & un-maintainable.
CQRS solves the common problem of having a bloated Domain objects. The domain objects get bloated largely because of bounded context. The series of contexts which makes developers think that a single domain object is sufficient to handle all the related things. For example, a large Invoice object for handling Invoice, Shipment and handling change of address for customer . But in reality, these contexts (invoicing, shipment and change) need not be related to same Invoice entity.
What is Command, Query Responsibility segregation (CQRS)?
In order to simplify the Domain objects, CQRS proposes to have two types of domain entities.
- those serving the command (ordering/assertion services) – For example, SaveCustomer, CreateInvoice, ShipProduct etc
- those serving a Query (request) – examples include GetCustomerAddress, SearchCustomer etc
With this separation, the complexity (number of fields, methods) of entities used becomes simplified. And hence the Data mapper layers & the service layers becomes more simplified.
Where can I use CQRS?
- Largely complex system: Applying CQRS on a simple CRUD operation based system is a over kill. When there is a domain heavy system, like banking and financing systems, LOB applications where business logic, lots of boundary conditions are heavy. Where it makes DDD (Domain driven design) provides high value.
- Situations where you will apply Microservices, Eventual consistency and Event Sourcing. When we have separation of concerns using CQRS, the microservices becomes much simpler to design and maintain. With Event sourcing we are focused on getting the data (query) from other related sources and is what CQRS propagates.
CQRS is a carefully thought out pattern for simplifying large and complex systems. And it should not be applied for simple green field applications. Do let me know what you think.