Skip to content

Command\Query Object Pattern

Rupesh Bhochhibhoya edited this page Jan 25, 2016 · 1 revision

The idea is to abstract out the data interaction logic into separate layer so that other part of application does not have to deal with these complexities. Repository pattern gets us to there by encapsulating all related data into seperate object. For instance if we have product concept in our application, the repository object that interact with datasource may look like this:

public interface IProductRepository
{
    IEnumarable<Product> GetProductById(in id);
    IEnumarable<Product> GetMostLikeProducts();
    IEnumarable<Product> GeLeastLikeProducts();
}

This list of functions could grow quicky based on requirements resulting thick repository object that is holding huge business logic. So, command/Query object pattern is about breaking down such repository class into granular object call query object which will be resposible only for one set of data corresponding to one query. For instance, for the same product repository with three functions, there will be three Query Objects:

public interface IProductQuery{
     IEnumarable<Product> Execute(Session session);
}


public class ProductByIdQuery : IProductQuery{
     IEnumarable<Product> Execute(Session session){
      return session....
     }
}

public class MostLikedProductQuery : IProductQuery{
      IEnumarable<Product> Execute(Session session);
}

public class LeastLikedProductQuery : IProductQuery{
      IEnumarable<Product> Execute(Session session);
}

Each of those query is given separate classification as it holds very important business logic. This pattern is test friendly and does one and only one thing in lieu of Single Responsibility Principle.

Clone this wiki locally