Repositories or Command / Query Objects?

This is a follow up post to my YouTube video Repository Pattern, Done Right. If you haven’t seen this video, it’s best to watch it first, before continuing reading.

There have been many interesting questions in the discussion area and I’ve replied to most (if not all) of them. One that has come up a few times is:

Should we favour command/query objects over repositories?

A few have referred me to Jimmy Bogard’s post. So, in this post, I’ll be comparing these two approaches and pros / cons of each.

Before I get started, I need to emphasise: neither the repository pattern, nor command / query objects, are silver-bullets. Just because these architectural patterns exist, doesn’t mean you should use them in every single application. If your queries are simple enough (one or two lines), don’t worry about creating an abstraction over them. There is nothing wrong with writing them in your controllers (assuming a web application).

If you do, however, have fat queries that have bloated your controllers, you might want to consider one of these patterns to achieve “better separation of concerns”.

Repository vs Command / Query object

In a repository, we often have many methods, all related to a specific entity:


When you promote one of these methods to a class, you’ll end up with what we call a query object.

public class GetPopularGigsQuery
     private GigsContext _context;

     public GetPopularGigsQuery(GigsContext context) 
          _context = context;

     public IEnumerable<Gig> Execute() 
          return _context.Gigs

So, what you see in the Execute() method here, used to be one of the methods of a class like GigsRepository. Now, we’ve promoted that to a class. Have we gained anything here? Absolutely not!

With this approach, if you have a repository with 5 methods, you’ll end up with 5 new classes in your application. Now, take into account how many repository classes you have and eventually how many command / query classes you’ll end up with. You’ll end up with an explosion of classes that don’t provide any additional value than a simple method.

When Command / Query objects provide value

When you want to execute some operation before and / or after the execution of the command / query. Sometimes, in large enterprise applications, you may want to check that the current user has permission to execute a given query (or command), and additionally you may want to log that somewhere.

Without using command / query classes, your repository methods would end up with a lot of duplicate logic:

public IEnumerable<Gig> GetPopularGigs()
     // authorisation logic 

     // logging logic 
     return _context.Gigs.......

public IEnumerable<Gig> GetUpcomingGigs()
     // authorisation logic 

     // logging logic 
     return _context.Gigs.......

At this point, by promoting a method to a class, you’ll have at least a couple of options in front of you to implement the same behaviour in a more elegant way. You can use the template or strategy pattern.

With the template pattern, you would define a base class for your commands or queries like this:

public abstract class Query 
      public void Execute()
           // authorisation logic 

           // logging logic

      abstract void DoExecute();

So, you write the authorization and logging logic only once, in the base Query or Command class. Then, when implementing an actual command or query, you override the DoExecute method:

public abstract class GetPopularGigsQuery : Query 
      public override DoExecute()
           return _context.Gigs....

With the strategy pattern, instead of using inheritance, you’d use composition to achieve the same thing. If you need more understanding of inheritance vs composition, check out my C# course: Classes, Interfaces and Object-oriented programming.

What about ASP.NET MVC action filters?

Mosh, aren’t action filters exactly for that? To execute some custom logic (e.g. like authorisation or logging) before each action? True! Then, why bother using the command / query pattern?

Good question! First, you don’t have to use the pattern, if you prefer to use ASP.NET MVC action filters. But what if, in the future, you decide to use a different web presentation framework that doesn’t have the concept of MVC filters? Tools and frameworks come and go. What is popular now, is not going to be popular in a few years time. There was a time we thought ASP.NET WebForms was so cool. Now, it’s almost a dead technology!

If you want to protect your application architecture from change of external tools and framework, you need to decouple it from them by creating your own abstractions. Command / query pattern is one of the ways to create such abstraction. If you switch over to a different presentation framework, you can take all your existing code and re-use it without modifying a single line, and more importantly, without breaking things along the way!

What if…

What if you’re not too concerned about decoupling your application architecture from external tools / libraries? What if you think this is overkill? That’s a perfectly valid argument. Then, don’t use these patterns. As I always say to my students: “Keep it simple”. Use MVC filters to achieve the same result, and if they won’t help you in the future, then you’d spend time solving that new problem, not now.

What if you don’t have such requirements like authorisation and logging before each query? Then, command / query objects don’t give you any additional value. You’ll just waste your time and energy writing more and more code.

What if you don’t have complex queries in the first place? Don’t bother with the repository pattern either!

Every pattern is designed to solve a specific problem. Don’t solve a problem that does not exist!

Till my next post, all the best my friends!



Related Posts

Tags: , , , ,

10 responses to “Repositories or Command / Query Objects?”

  1. Stilgar says:

    Promoting the query to a class does have value. If you have too many queries over a single repository you need some tools to split them and work with them in an easier way. In C# this way is classes. You can organize classes in separate files (i.e. you do not end up with 5000 lines class), you can put them in folders and so on. The tools we use are optimized for working with the unit class not the unit method.

  2. Erik says:

    Clearly, you don’t understand why command/query objects exist. It’s called Command/Query separation (not to be confused with CQRS, which is a related, but different concept).

    The point of separating your commands from queries is that queries should be idempotent. In addition, by separating them into objects you get the ability to easily add cross cutting concerns to them via decorators. You should really read Steven’s very detailed blog entries:

    • admin says:

      Erik, thanks for your comment. The posts you’re referring to are nothing new. The first time I read about command and query separation was more than 5 years ago on Udi Dahan’s blog (not a full CQRS implementation, just separation of commands and queries and an in-process bus). Jimmy Bogard also has a Mediator project on GitHub that is based on the exact same concept. After implementing command/query objects in a few projects, I’ve come to this conclusion that if you don’t have to handle cross-cutting concerns, promoting a repository method (which is query in nature) or a service method (which is command in nature) to a class, adds no additional value. Sure, we can rationalise that we’ve adhered to single responsibility principle, and as Uncle Bob says, our classes now have a single reason to change. But does this solve any business problems? Probably not!

      I’m guessing you fast forwarded to express your strong opinion before reading my post to the very end! :)

  3. Recep says:

    Hey Mosh,

    First of all, I read your article a few minutes ago. It’s very explanatory. I will check template and strategy pattern.Also I want to follow your website via rss but, it doesn’t work. please check and solve this problem. :)

  4. Larry Q says:

    Thanks for this, it’s very helpful, showing both the pro and con cases for promoting query methods to classes. I fall into the first camp more often than I should, and it’s good to have a ‘cheat sheet’ to go back to for determining when to stop, and split things into their own classes. (Likewise, nice to know when a non-pure implementation is good enough.)

    Do you have any thoughts on aspect oriented frameworks outside of the MVC action filters? I personally haven’t used any and would like to know what fits your bill these days.

Leave a Reply