asp.net-mvccommand-query-separation

CQS and ASP.NET MVC Actions


Those who have read about CQS principle know that:

CQS states that every method should either be a command that performs an action, or a query that returns data to the caller, but not both.

Speaking of ASP.NET MVC Actions, does CQS indicate that we shouldn't have an Action like this?

public PartialView InsertOrder(Order order)
{
       OrderService.InsertOrder(order);
       return PartialView("OrderDetails", order);
}

This method is changing the state of the system and returning the current state. If CQS is applied here, we should have 2 separate Actions: one for inserting a new order and one for getting the system of the system (which should be called from the client if the first Action was completed successfully). However, this complicates programming.

I'd like to know your opinions on this.

Mosh


Solution

  • I had a vague recollection of this term from the eiffel days (which if followed all the way back, actually predates most current oop principles by a good decade or so (late 80's i think). I'd suggest that this term and/or principle may well be outmoded now and superceded by actionresults in mvc (be that asp or codeignitor etc, etc). I actually think that in terms of the definition (which i just looked up now), this separation is concerned with the logic that performs the action i.e. OrderService.InsertOrder(order) in your example. So, in a way, mvc as performed in your action is actually loosley following this pattern (InsertOrder doesn't attempt to present any stateful info, purely process the order object).

    I'd suggest that you look at best practice for asp.net mvc which is fundementally based on returning an actionresult (or partial, contentresult etc, etc). this pattern was designed to simplify the paradigm to facilitate productivity in a uniform and universally accepted fashion.

    of course, you could use your action return values to generate a success or fail for the insert/update/delete scenarios and then request partial views based on those return value. However, i personally don't think i'd leverage too much value from that approach bearing in mind the fact that the controller in MVC is concerned with stearing the logic of which view should be returned as the result of an action.

    hope this helps

    jim