The MVVM Pattern Is Highly Overrated

102 commentsWritten on July 21st, 2010 by
Categories: Architecture, Code Quality, Silverlight

Update: check out my MVP In Silverlight/WPF series which discusses the MVP approach as an alternative to MVVM

If you're doing Silverlight or WPF, you've no doubt come across the MVVM (Model-View-ViewModel) pattern. It seems to be the most popular client-side architecture pattern used among Silverlight/WPF developers. I find the pattern to be highly overrated, and actually have some big issues with the whole thing.

First, let's briefly cover what MVVM is about for those of you who don't know yet. MVVM virtually eliminates all of the code that would typically be placed in the code-behind file of your View (a user control, a screen, whatever) by putting all of that logic in the ViewModel. The ViewModel itself is never tightly coupled to the View. If it does have a reference to it, it's typically through an interface that the View implements instead of a reference of the actual type of the View. This increases, or better yet, introduces testability to a large part of your UI code that you normally wouldn't be able to cover with unit tests if you'd go with the traditional "put it all in the code-behind"-approach.

The ViewModel typically contains properties for the data that is to be shown in the View, and also raises notification events when the data in those properties changes. The View uses the powerful data-binding capabilities of Silverlight/WPF to bind the properties of the ViewModel to other user controls that the View is composed of. User-events that are captured by the View are sent to the ViewModel through Commands. Typically, these commands execute a method in the ViewModel which contains some kind of logic... usually to either send the updated data in the ViewModel's properties to the Model (usually a Service Layer in Silverlight, in WPF it could be either a true Domain Model or also a Service Layer), to perform some business logic in the Model, or to retrieve data from the Model so it can be placed in the ViewModel's properties so the View can bind to it.

That is, in a nutshell, how the MVVM pattern works. So why do i have issues with this? You can develop and test most of the application's logic without being dependent on a physical View and that is typically a Good Thing, no? It sure is! However, my problem with this approach is that too many responsibilities are concentrated within the ViewModel. Its main responsibilities are to facilitate databinding and to interact with the Model. And that, in my opinion, isn't very clean. In some ways, you could actually think of the ViewModel as a glorified code-behind, with the only difference being that it's not tightly coupled to the (physical) View.

In most (if not all) MVVM implementations, a ViewModel has many possible reasons to be changed. It might need to be changed because of different data-binding requirements. Then again, it might also require changes when a part of the Model is modified. Now, i'm sure many of you can agree with me when i say that two of the most important principles in software development are Seperation of Concerns (SoC) and the Single Responsibility Principle (SRP). Obviously, the ViewModel doesn't fare well when it comes to both of these principles.

Lets forget about MVVM for a second and focus on the concerns and responsibilities that a user control can have... say, a user control that shows customer information and allows the user to edit that data so it can be persisted:

  • visualization of the actual control (its own layout as well drawing other user controls that it is composed of)
  • communication/interaction with the Model
  • making data (from the Model) available so it can be displayed
  • outputting data in the correct user controls (for instance: various textboxes)
  • (simple validation) of modified/inputted data (for instance: no string values for numeric fields, etc...)

Without MVVM, all of these would be taken care of in the View. Obviously, not a good idea right? After all, if it were a good idea, we'd never have had a reason to start using MVVM in the first place.

Now, with MVVM, a lot of people would divide these concerns and responsibilities like this:

View:

  • visualization of the actual control (its own layout as well drawing other user controls that it is composed of)
  • outputting data in the correct user controls (for instance: various textboxes)
  • (simple validation) of modified/inputted data (for instance: no string values for numeric fields, etc...)

ViewModel:

  • communication/interaction with the Model
  • making data (from the Model) available so it can be displayed

In this case, the View still has 3 responsibilities which is still too much according to 'the guidelines', but it's not that big of a deal (though plenty of people would argue that the simple validation would be better placed in the ViewModel). You're highly unlikely to actually want to write automated tests for pure visualization anyway and the SRP is not something that you absolutely need to follow to the extreme in every single place. For the View, this is really not a problem and very much acceptable.

The ViewModel however has 2 important responsibilities in this case, and i'd argue that these 2 things should not be done in the same place. Making data available is done through data-binding. To do this, you need a set of properties and you need to raise the necessary events. In most cases, raising those events is very straightforward, but in more complex controls you might need a bit of additional logic to determine which event should be raised at what point. The other important responsibility is the communication/interaction with the Model. In most Silverlight applications, the Model will be a Service Layer. To communicate with this Service Layer, you need Service Proxies. That means that your ViewModel is essentially responsible for communicating with the Service Layer, dealing with business exceptions that might be thrown by some service calls, and dealing with technical exceptions that can occur simply because of network-related problems. Group all of those together and i don't think i'm going out on a limb here by saying that that is a lot of logic to put in one class, no?

(Sidenote: what i don't really understand is that many people who vigorously advocate adherence to SRP and SoC in their domain and business code don't seem to hold their UI code to the same standards. I do.)

At work, we do a lot of Silverlight development. We typically have around 5 Silverlight projects in active development at the same time. And it's been that way for over a year now. That equals a lot of Silverlight code that we've written and experience and knowledge that we've built up. And we haven't used MVVM for any of it. All this time, we've been using the MVP pattern (Supervising Controller variant) with a slight twist. That twist being a slimmed down version of a Presentation Model. Our Presentation Model's sole responsibility is to facilitate data-binding, and in some cases, a touch of validation is added as well.

If we go back to our previous example of the customer screen, the responsibilities and concerns would be divided like this in our MVP-PMlight approach:

View:

  • visualization of the actual control (its own layout as well drawing other user controls that it is composed of)
  • outputting data in the correct user controls (for instance: various textboxes)
  • (simple validation) of modified/inputted data (for instance: no string values for numeric fields, etc...)

Presenter:

  • communication/interaction with the Model based on the contents of the Presentation Model

Presentation Model:

  • making data (from the Model) available so it can be displayed

Which leads to classes which are more focused on their task instead of trying to focus on too many things at the same time. In my opinion, this approach is much better/cleaner than MVVM. Not only is there a noticeable benefit in code quality (classes are more focused), there is also increased potential to reuse our 'light Presentation Models' in multiple controls. Testability is increased over MVVM as well since it's always easier to test classes which are focused versus testing classes which have too many responsibilities. All in all, a couple of important benefits and we still haven't thought of a real drawback compared to MVVM.

  • http://sergejus.com Sergejus

    Davy, I totally agree with you, but I’d suggest to take a look at MVC-MVVM hybrid – MVVMC. In this case ViewModel responsible dor data-binding stuff and Controller responsobility is to communicate with the model.

  • Stephen Patten

    Davy,

    I agree with you on an academic level because i am just beginning to work with the various MVVM frameworks (i.e. MVVM Light, Caliburn.Micro, and Prism4), would you be kind enough to post a quick start of your framework with the various pieces broke out correctly?

    Thank you,
    Stephen

  • http://randallbits.com Randall Sutton

    I totally agree. I blogged about the same thing a little while ago MVVM is the New Code Behind

  • Lars-Erik Roald

    I understand what you are saying – but I’m not sure I agree. The few examples I have seen with dividing the logic between controller and viewmodel has been either awkward or too simplistic for real life. I usually nest a complex viewmodel into several subviewmodels and subviews – and the views have explicit regions that are to be filled with subviews. E.g. IOrderView.OrderHeaderRegion, IOrderView.OrderDetailsRegion. Then I fill the subregions: _view.OrderHeaderRegion.Add(_orderHeaderViewModel.View)…. This way each viewmodel and view becomes fairly easy. I use viewmodel first approach.
    The “parent” viewmodel is not agnostic about it’s subviewmodels and views – it has direct references to them (via constructor injection).

    Anyway, the viewmodel should just use services to prepare Dtos for display. E.g. _orderLinePresenterFactory.Create(_orderlines). And communication is also triggered by the viewmodel by calling some serviceLayerProxy. I don’t see the problem her . Could you provide a code sample to clearify things ? (not too simplistic, maybe with some events from the view)?

    (About the sidenote: I have noticed this too. There are some extremely skilled gurus out there with very bad clientside code – surprisingly.

  • Ryan

    It all depends on your definition of responsibility. In your example above, the 2 “responsibilities” of the ViewModel are not really 2 responsibilities – more like 2 tasks necessary to fulfill 1 responsibility. “making data (from the Model) available so it can be displayed” can easily be thought of as contained in the “communication/interaction with the Model” responsibility. Likewise for your 3 View responsibilities. The real responsibility of the View – to display the UI – is quite simple. All the complications that enable that responsibility are really not that important. You could sit down and come up with a list of a dozen or more View “responsibilities” if you wanted to get detailed enough. But ultimately, all those tasks are working toward fulfilling the same responsibility – displaying the UI – which is all that SRP means.

    I have worked on a project where the Presenter logic was separated from the presentation of the model. It was a lot of extra work and we all agreed when the project was over that it was going to be a maintenance nightmare. The reason is that about 1/2 or more of the code in the Presenter and the PresentationModel is duplicate code. What’s the point of creating a separate PresentationModel when the Presenter already has to retrieve the Model object and do work with it? Why not just expose it to the UI from the Presenter (ViewModel)? Is it really all that more complicated to add a property? No – it’s much less complicated than duplicating all the code to retrieve the Model objects from the service in each Presenter/PresentationModel class.

    There is nothing wrong with the pattern you describe really, but I see it, particularly based on my experience, as overkill.

  • Josh Schwartzberg

    I second a concrete example to show us what the implementation looks like.

  • http://www.tjsolutions.nl Tom de Koning

    yep, show me the code!

  • http://davybrion.com Davy Brion

    @Stephen

    “would you be kind enough to post a quick start of your framework with the various pieces broke out correctly?”

    i’ll try to get something like that up soon, though i can’t really promise when that will actually be :)

    @Lars-Erik Roald

    “Anyway, the viewmodel should just use services to prepare Dtos for display. E.g. _orderLinePresenterFactory.Create(_orderlines). And communication is also triggered by the viewmodel by calling some serviceLayerProxy. I don’t see the problem here.”

    like i said: i think the PresentationModel should focus (almost) exclusively on making data-binding possible. That means providing the necessary properties that raise the PropertyChanged event, as well as the ones that don’t need to raise that event. For some properties (whose values are used by ‘calculated properties’) that also means raising multiple PropertyChanged events. I think those things are one distinct responsibility and i really don’t want any communication with the model to be mixed with that, since that is (IMO) a completely separate responsibility

    @Ryan

    you can make your responsibilities as coarse-grained or fine-grained as you want. If you consider “displaying the UI” to be one responsibility, then we obviously disagree. If that were one responsibility, you could consider everything that is *required* to display the UI (for instance, fetching the data) to be a part of that same responsibility. In that case, you could just as well put it all in the code-behind because it’s all part of one responsibility anyway and you wouldn’t be in violation of the SRP. I really can’t look at it that way.

    ‘making data (from the Model) available so it can be displayed’ is what i consider to be => facilitate data binding. As mentioned in the post and earlier in this comment, i don’t consider that to be related to retrieving the data from the model. To me, both are separate steps and should be dealt with separately.

    “I have worked on a project where the Presenter logic was separated from the presentation of the model. It was a lot of extra work and we all agreed when the project was over that it was going to be a maintenance nightmare. The reason is that about 1/2 or more of the code in the Presenter and the PresentationModel is duplicate code.”

    I really don’t understand this… we _never_ have duplicate code between our presenter and our presentation model. I can’t even think of a way how you could end up with duplicate code between them if your presentation model just facilitates data-binding while your presenter communicates with the model. The presenter doesn’t have the same properties as the presentation model… it contains the presentation model and uses it to store the data retrieved from the model. If the data can be modified by the user through the view, the presenter can then retrieve the modified data from the Presentation Model and send it back to the model.

    Maybe there’s something you misunderstood about our approach with regards to the duplicate code thing… could you provide more details of what kind of code would be duplicated in both places? Keeping in mind that our presentation models are incapable of communication with the Model of course…

    “There is nothing wrong with the pattern you describe really, but I see it, particularly based on my experience, as overkill.”

    in our experience, it actually ends up making things simpler :)

  • http://digitaltapestry.wordpress.com wekempf

    *sigh*

    “All this time, we’ve been using the MVP pattern (Supervising Controller variant) with a slight twist. That twist being a slimmed down version of a Presentation Model.”

    Presentation Model and View Model (or Model-View-ViewModel, see http://wekempf.spaces.live.com/blog/cns!D18C3EC06EA971CF!797.entry?sa=547377752) are one and the same pattern. All of your complaints aren’t really about the pattern, but about how the pattern is implemented, as evidenced by this one mistake in not knowing that Presentation Model and View Model are two names for the same pattern.

    • http://simonmassey.clavid.com/ Simon Massey

      When is a ViewModel not a PresentationModel? My answer is when it is implementing the Mediator pattern. A model which is just formatting raw dates and numbers to a users locale is not a model of the GUI. It is simply a presentation model (i.e. purely supporting value conversion). A more ambitious thing for a ViewModel to attempt is the Mediator pattern orchestrating the OO Model or Data Model. 

      To me Davy’s is saying “the plumbing of the mediation” gets in the way and that a “simple formatting model” with “separated controller” works better for him. Saying that ViewModel is a PresentationModel misses the distinction between mixing the orchestration of the Model into the ViewModel else keeping it separate. 

      I think that the reason that MVVM is so much alphabet soup to most people is that after half a decade the documentation does not yet pick up on Mediation being (a possible) facet of the pattern. It is of course optional; but I think it is central to what Davy is discussing and is at the root of the mis-understanding which lead to the flame war here….

  • http://davybrion.com Davy Brion

    @Wekempf

    what part of ‘slimmed down version’ did you not understand?

  • Josh Schwartzberg

    Davy,

    I have a ‘feeling’ that the next version of C# will be more like Objective-C and intercept messages and automatically notify anyone subscribing. At this point, would you get rid of your presentation model classes and just expose the properties and other events directly on your presenter?

  • http://davybrion.com Davy Brion

    @Josh

    that wouldn’t be sufficient in the case of ‘calculated properties’ so no, i wouldn’t

  • Josh Schwartzberg

    Makes sense. Which class is in charge of determining which view to display, and how does it go about making the view actually show up in the ui in the first place?

  • http://digitaltapestry.wordpress.com wekempf

    @Davy Brion, what part of “PM and VM are the same pattern” did you not understand? I could care less if you slim it down, it’s the same pattern. You can’t say you don’t use VM, then turn around and say you use a slimmed down PM. Seriously. You’re points about SOC and SOLID are valid, but violation of these principles can be done when implementing ANY pattern. VM doesn’t lead to the problem here, and you can follow VM without violating SOLID principles. AS YOU JUST ADMITTED TO DOING.

  • http://davybrion.com Davy Brion

    @Josh

    We always have one ‘root’ control which is the one that is instantiated initially upon application start-up. Since we use MVP instead of MVC, the View is created first and resolves the presenter through the IOC container. So, the root UI component is instantiated, it resolves its presenter and from there on, it kinda depends. If there’s a menu, we’ll (obviously) go to the View of the selected menu item. If it’s a dashboard-kinda interface, there’s usually multiple views through which the user can navigate to other parts of the application.

    Not entirely sure if this is what you wanted to know, so if i missed the intent of your question, feel free to ask it again in a different manner ;)

  • http://jmorrill.hjtcentral.com Jeremiah Morrill

    IMHO, you are doing MVVM. You have a model, a view and a view model/presentation model. Much like the observer-pattern (very general) can be done with sinks, delegates/events, etc, the concept is the same even though the implemenation is very different.

    -Jer

  • http://davybrion.com Davy Brion

    @Wekempf

    “I could care less if you slim it down, it’s the same pattern”

    if the behavioral part of the pattern is missing or significantly different, then clearly, we can’t really consider them to be identical, no? Our presentation model does NOT have any kind of behavior outside of what is necessary for data-binding. It does NOT communicate with the Model, which is a very important part of the ViewModel pattern, right?

    Now, in that sense, the Presentation Model is probably a poorly chosen name… Then again, some people consider Presentation Model and ViewModel to be the same, and others don’t. You make of it what you want, and i will make of it what i want.

    “You’re points about SOC and SOLID are valid, but violation of these principles can be done when implementing ANY pattern.”

    Depends on how you implement the pattern and it also depends on how high-level or low-level the intent/description of the pattern is. In the case of MVVM, the pattern is pretty clear: communication/interaction with the model is done in the VM, which is what i consider to be a serious violation of the SRP. In our approach, that violation is not present.

    “VM doesn’t lead to the problem here, and you can follow VM without violating SOLID principles. AS YOU JUST ADMITTED TO DOING.”

    once again: VM is supposed to interact with the model, which results in the violation. And no, i didn’t admit to doing that… you are too hung up on the usage of the Presentation Model name. If you would actually _think_ about the difference between my version of the Presentation Model, and the widely used definition of the ViewModel, you can’t seriously consider them to be the same.

    Would it help you if i renamed my Presentation Model to a SloppyJoe or something like that?

  • http://davybrion.com Davy Brion

    @Jeremiah

    i disagree… a very important part about any pattern is how you deal with behavior. if the behavior is dealt with in a different manner, then you can’t consider them to be the same

    it’s like saying MVC and MVP are the same
    large similarities still doesn’t mean it’s the same

  • http://digitaltapestry.wordpress.com wekempf

    @Davy Brion

    “If you would actually _think_ about the difference” implies I haven’t, which isn’t evidenced anywhere in my responses. It’s rather offensive. If you’d not “underlined” the think I could forgive it as a misunderstanding, but at this point it’s rather obvious you’re flaming. Going to make it very hard to have an intelligent conversation about the topic, so I’m bowing out. Have fun splitting hairs with anyone that cares.

  • Lars-Erik Roald

    @Wekempf please behave. Let Davy have time to create some example code.

    And, yes, the concepts are easy to mix – because one pattern is a specialization of the other.
    Splitting databinding and communication handling sounds appealing to me – but I just don’t believe it yet…but I might change my mind when I see the code. :-)

  • http://davybrion.com Davy Brion

    @Wekempf

    The fact that you keep going on and on about how it’s the same while there is a major difference in the implementation and that you keep focusing on the name does kinda imply that you didn’t really think it through IMO

    If you consider that to be flaming, that’s too bad.

    though i’m glad that we can at least agree that the usage of all caps is different from using ‘underlining’ when it comes to flaming. even though our reasons to agree would differ.

  • http://davybrion.com Davy Brion

    @Lars-Erik Roald

    it’ll probably be either during or after the weekend though

  • Anthony

    This article’s points (UI independence, Separation of concerns and SRP) don’t really argue in favour of going back to code-behind. they argue if favour of going to MVVM and then going further.

    If you feel that the ViewModel is doing to much, then yes, split the actions out into command classes that work upon it and leave the viewModel just as a source of binding data.

  • http://davybrion.com Davy Brion

    “This article’s points (UI independence, Separation of concerns and SRP) don’t really argue in favour of going back to code-behind. they argue if favour of going to MVVM and then going further.”

    well yeah… going back to code-behind is something i’d never recommend and MVVM is just not good enough IMO :)

  • http://digitaltapestry.wordpress.com wekempf

    @Lars-Erik Roald

    Behave? Really? What did I do that wasn’t behaving?

    @Davy Brion

    The all caps were making a point through emphasis, not flaming. You’re underlining also was for emphasis, but what was emphasised was a flame. There’s a distinct difference here.

    BTW, as evidenced by the blog post I linked to, I’m hardly hung up on the name, beyond the need for clarity in communication. I don’t care what name you use, you stated that your code followed the pattern. You do split hairs about the implementation, but patterns aren’t about implementations. Based solely on your description, what you’ve done fits the VM pattern, even if you implemented differently than someone else has. So, my issue isn’t with the technical merits of your design, but with yet another “my implementation is different from yours so I must be using a different pattern” posting that just leads to further confusion.

  • http://davybrion.com Davy Brion

    @Wekempf

    “You do split hairs about the implementation, but patterns aren’t about implementations.”

    Well, that is something that we just fundamentally disagree on then. It’s not about the actual implementation on a line-per-line basis, but i do consider where you put certain behaviors to be a very important part of a pattern description/definition, especially when you’re talking about high-level patterns like MVVM, MVP or MVC

  • http://shadowcoding.blogspot.com Erik

    Put me on the list of those interested in some sample code! =) I’ve been trying to deal with the same issue you have, though I’m a neophyte in both WPF and MVVM.

  • http://www.adefwebserver.com/ Michael Washington

    I created some examples of “View Model”. Basically it is like MVVM, but concentrates on using less code than you would need for code behind and also allowing the Designer full freedom to change the design.

    RIATasks: A Simple Silverlight CRUD Example
    http://www.codeproject.com/KB/silverlight/RIATasks.aspx

  • Vagif Abilov

    Davy,

    It will be interesting to see some code examples to illustrate your points. I don’t think your message is clear enough without it.

  • Pingback: The Morning Brew - Chris Alcock » The Morning Brew #648

  • Pingback: Single Responsibility Misuse « This Hours Eternity

  • ross

    It’s an interesting discussion point. From what I can tell, everyone sensible agrees on a separated presentation layer, which xaml enables nicely, but the rest of the debate is just semantics and implementation details.

    It is axiomatic to say that anyone who is doing separated presentation smelling design will have to create a class or classes which provide the incoming and outgoing binding interface of a particular view. On top of that, a further set of infrastructure classes will probably be needed to instantiate and manage those binding classes and the views. How you design the non-presentation layer is interesting and important, but the best approach depends on a number of factors, e.g. project complexity, team size/project methodology, future requirements and projects, requirements for plugability, testability, design requirements…….

    Some implementations will be better than others, so I vote for the code sample. 500 lines of code will tell 5000 words, and will take the reader 1/50th of the time to comprehend the meaning of your take on this.

  • http://davybrion.com Davy Brion

    as mentioned earlier: a detailed code sample will be posted during or after this weekend

  • http://www.planetgeek.ch Daniel Marbach

    I would go for MVVMP, namely Model View ViewModel Presenter pattern. The presenter interacts with the model and translates data from the model into bindable data which is attached to the ViewModel.

  • http://dotenetscribbles.blogspot.com/ tugga

    We use a variant of MVVM pattern, wherein we have Model, View , ViewModel and Controller. The controller can further have micro-controllers. Our ViewModel has only properties which are needed by the view. It delegates all other responsibilities(which you have mentioned above) to the controller using events or mediator pattern. The controller can delegate a request further to a micro-controller. It it the responsibility of the controller to talk to the model and populate ViewModel properties. This approach facilitates SOC and SRP.
    The MVVM pattern is highly overrated because it allows unit testing at all levels. Further, you can write do end-to-end testing by simulating clicks(using commands). MVVM is a great pattern if you use it correctly.

  • http://Www.digitaldias.com Pedro Dias

    The view model in the mvvm pattern is just that : a model of the view. I would not presume most of the business view that I write to be a mere display of static values. A view model has properties as well as behavior (buttons, property selections, sliders). Now, i saw a reply stating that mvvm is the new code behind as I’f it was a bad thing when in fact, this is the whole idea of the pattern! Make the code behind completely independent of the guy, so that you can unit test the GUI behavior.

    Honestly, I fail to see the authors point. Does it violate SRP? No! The VM has one single responsibility, and that is to represent a GUI. Are there separate concerns? Again no. One could argue that the VM holding a service reference might give a few extra headaches, but for all intents and purposes, at some point, a service reference to the view must be made.

    I’ve had some concern about the complexity of the view model classes myself ,but realized after some time that I was trying to do too much in a single view, something that has led me to keep my views simpler. And the effect? Customers love it.

  • http://davybrion.com Davy Brion

    @Pedro

    one simple question: should all logic of handling a service request be implemented in one single class? If your answer to that question is yes than you indeed fail to see my point. If your answer is no, then i’d like to ask you: what is the difference?

    after all… handling the service request is the only responsibility, right?

  • http://Www.digitaldias.com Pedro Dias

    The view itself has one responsibility, and that is to connect th non-gui end of some service class to the end user. This involves 2 aspects: the graphical bit, and the code thAt connects it to the service.

    The typical example, some input form with an OK and CANCEL button, a list of possible values for a property etc.

    The view itself a listbox, some text boxes and a couple of buttons.
    What you need to back these are
    - properties to hold your values
    - some services to supply you with listbox contents
    - some service to chew on the users input.

    All of these tied together form the dreadful code behind. This is where your SOLID principles meet at the end, right at the end users nose.

    If, during testing, a end user finds that something odd happens if he clicks that button before the other one, that is now something that you can create a reliable test for. You don’t have to set up a bunch of satellite code to recreate the problem, you just ask the view model to press this and that button, possibly with the services moq’d away.

    The VIEW as I have come to understand the pattern, is an isolated user experience, a scenario that helps the user solve a particular task. The view model is where all of the SOLID principles come together to support it, almost in a cucumberish way.

    HOWEVER, and this is important:
    You Are right in that traditional view design, such as a complex order form can quickly lead to completely ridiculous viewmodels. The trick is to apply SRP to the design itself. Separate the view concepts as rigidly as you do the code, and you quickly find that bloat is a thing of the past. Hints: start out by creating a view for every value class you have. Remember that view models can and should contain view models. Binding directly to data is a no no. An OrderViewModel class should naturally have an observablecolection of OrderLineViewModels, a CustomerViewModel, etc. These are all individually fortified by unit tests. I see far too many people complicating their lives by having that orderviewmodel contain a list of ordereline objecs. This leads to instant code bloating, and violates at least half a dozen principles.

    Some of my most complicated views are all designed like this, and rarely consist of more than two or three properties, some event stitching (I do use the. Mediator/EventAggregator pattern with mvvm). IOC takes care of the object stitching for me.

  • http://davybrion.com Davy Brion

    @Pedro

    “The view itself has one responsibility, and that is to connect th non-gui end of some service class to the end user.”

    As i’ve mentioned before, that is way too coarse grained. Retrieving data from the Model, transforming it a ViewModel structure/hierarchy, notifying the View of changes, and sending changes back to the Model is currently all concentrated within the ViewModel… i really can’t agree on all of that being ONE responsibility

    “The view model is where all of the SOLID principles come together to support it”

    grouping a bunch of code together in one class is does not mean you’re writing SOLID-compliant code… i think there will be very, very few situations where that actually turns out to be the case

    You really don’t have to take my word for it… maybe it’ll help if we involve code metrics into this discussion. Good OO code is highly cohesive, and loosely coupled. Loose coupling is easy to achieve, but writing cohesive classes is another matter that very few people seem to be capable of doing.

    Cohesion of a class increases as its fields get used by most (if not all) of its methods. As you keep piling on extra logic in a class, cohesiveness obviously decreases, unless most of the fields are still being used by most of the methods that implement that extra logic.

    Now, as i’ve stated in the post and in my comments, the ViewModel simply does too many different things. Can you at least agree with me that this decreases the cohesiveness of the ViewModel? And if so, how do you think that relates to how well it’s following the SOLID principles?

  • Mikey

    I like the MVCVMPCMVMP pattern. Model-View-Controller-ViewModel-PresenterController-ModelViewModelPresenter. Guaranteed to keep me in employment for at least 5 years while everyone else tries to figure out exactly what the hell it does.

  • http://www.digitaldias.com Pedro Dias

    I am currently working on a movie inventorizer application. Among other things, a movie has a concept called “A format”, which denotes if it’s a DVD, VHS, Blu-Ray, or some other format. The domain object is straight forward:


    public class MovieFormat
    {
    public int Id{ get; set; }
    public string Name{ get; set; }
    }

    Because this is a concept that I wish to visualize, I write a view for it:
    (took out the non-essencials). I hope XAML lends itself well for pasting into this reply


    (In case it doesent: It’s really just a small grid with two bound properties: an icon, and the name of the format)

    Now all that is missing is the viewModel:


    public class MovieFormatViewModel : BaseViewModel
    {
    private IMovieFormatIconManager _iconManager;
    private MovieFormat _movieFormat;
    private WriteableBitmap _iconFile;

    public MovieFormatViewModel( MovieFormat movieFormat, IMovieFormatIconManager iconManager )
    {
    _movieFormat = movieFormat;
    _iconManager = iconManager;
    }

    public WriteableBitmap IconFile
    {
    get
    {
    if( _iconFile == null )
    ResolveIconOrUseDefault( );

    return _iconFile;
    }
    }

    public string FormatName
    {
    get
    {
    return _movieFormat.Name;
    }
    }

    private WriteableBitmap ResolveIconOrUseDefault()
    {
    if( _iconManager == null )
    throw new InvalidProgramException( "No icon manager found" );

    WriteableBitmap result = _iconManager.GetIconForMovieFormat( _movieFormat );

    if( result == null )
    return _iconManager.DefaultMovieFormatIcon;

    return result;
    }

    }

    At the risk of repeating myself into stupidity, the whole idea behind the MVVM pattern is to represent a view through a class.

    I believe that what you are not seeing is that a view is as isolated as code that follows the SOLID principles. You do not write one huge class for an entire operation, such as “create order form”; a view is not analogous to a form in WinForms. It’s analogous to a domain object.

    At a later stage, there will be a MovieEntry:


    public class MovieEntry
    {
    public Movie Movie{ get; set; }
    public MovieFormat Format{ get; set; }
    public StorageLocation StorageLocation{ get; set; }
    }

    ..with a corresponding view and viewmodel class:


    public class MovieEntryViewModel
    {
    private IMovieEntryManager _movieEntryManager;

    private MovieEntry _movieEntry;
    private MovieFormatViewModel _movieFormatViewModel;

    public MovieEntryViewModel( MovieEntry movieEntry, IMovieEntryManager movieEntryManager )
    {
    _movieEntry = movieEntry;
    _movieEntryManager = movieEntryManager;
    }

    public MovieFormatViewModel MovieFormat
    {
    get
    {
    if( _movieFormatViewModel == null )
    CreateMovieFormatViewModel( _movieEntry.Format );

    return _movieFormatViewModel;
    }
    }

    // etc...

    I do hear your arguments. From my example, I am guessing that you do not like the manager objects injected into the viewmodel classees, and this is where we differ in our opinions.

    If you can come up with a MORE cohesive way of writing this code in a different pattern, then by all means, I am willing to learn it, but so far, MVVM is the most testable, easy-to-read pattern that I’ve had the pleasure of working with.

  • http://davybrion.com Davy Brion

    @Pedro

    “a view is not analogous to a form in WinForms. It’s analogous to a domain object. ”

    I disagree since that doesn’t translate to task-based UI’s at all.

    “From my example, I am guessing that you do not like the manager objects injected into the viewmodel classes, and this is where we differ in our opinions. ”

    indeed… to me, those ViewModel should focus on facilitating data-binding but should not interact with the model in any way. In my upcoming sample, i’m going to rename them to BindingModels to (hopefully) make the intent and the difference more clear.

    Btw, apart from interacting with the Model in the ViewModels, i do think we agree about ViewModels containing other ViewModels… though in my case, it would be BindingModels with no additional logic… that’s going to remain in the Presenter

  • http://www.digitaldias.com Pedro Dias

    I look forward to seeing your example.
    Please also include one or two of the tests, I’d love to see how readability on those are compared to mine:


    [TestMethod]
    public void PressDelete_ViewModelContainsMovies_MovieCountIsDecreasedByOne( )
    {
    // Arrange
    MovieEntriesViewModel entriesViewModel = CreateTestableEntriesViewModel( );

    int initialEntryCount = entriesViewModel.Entries.Count( );
    int expectedCount = initialEntryCount - 1;

    // Act
    entriesViewModel.PressDelete( );
    int resultingEntryCount = entriesViewModel.Entries.Count( );

    // Assert
    resultingEntryCount.ShouldEqual( expectedCount );
    }

  • http://davybrion.com Davy Brion

    about the code samples: i’ve given this some thought and i’ve decided to write a series of posts about this topic… one post would grow too large and most people simply don’t read those thoroughly

    i want to get the series up as soon as possible, but i do want to take my time for it, so it’ll probably be online within the next 2 weeks instead of this weekend

    the style of the series will be very similar to that of the Build Your Own Data Access Layer and Request/Response Service Layer series

  • http://blogs.claritycon.com/blogs/peter_miller/default.aspx Peter Miller

    While I find the semantic argument of MVVM vs. MVP vs. SloppyJoe uninteresting, I am really looking forward to a code sample as well. Thank you being willing to go above and beyond to respond to the critiques in the comments and give us all a chance to learn from what you’ve done. And for being direct in challenging the seeming dominance of the MVVM pattern in SL development these days.

    I am pretty new to the MVVM pattern, but after working with several MVVM-style applications, I also get a bad feeling when I see a ViewModel holding a service reference (or what Pedro calls a manager) to communicate with the model. If nothing else, it can also lead to problems when you stack up view models and suddenly have a whole mess of possibly redundant service calls being made.

    • Simon Massey

       @14b830ec68fdd932f933eea6aa2977d5:disqus when you say “a bad feeling when i see a ViewModel holding a service reference” that is something I call the “mystery guest” anti-pattern. You wished you were working with a poco and had Dependency Injection but instead things can break down into spaghetti logic and unexpected side effects of accessing harmless looking properties.

      What I am taking away from the discussion is that in SL where the pattern is “client side” the dispatch and plumbing to the server should not be “mounted” into the poco the View is bound to. Instead use the poco as the abstraction of the view that a controller pushes up into.

      On the flip side if you are not in SL and are doing MVVM in WPF fat client with ORM then the “remoting and dispatching” plumbing may not be a barrier to working directly with the model. Then the bindings can “pull through” the Model through the ViewModel to update the View. Regular commands going down then don’t need much plumbing and you can move your Use Case service Mediation logic into your ViewModel without the headaches of SL event dispatching to the server and the callbacks. 

    • Simon Massey

       @14b830ec68fdd932f933eea6aa2977d5:disqus when you say “a bad feeling when i see a ViewModel holding a service reference” that is something I call the “mystery guest” anti-pattern. You wished you were working with a poco and had Dependency Injection but instead things can break down into spaghetti logic and unexpected side effects of accessing harmless looking properties.

      What I am taking away from the discussion is that in SL where the pattern is “client side” the dispatch and plumbing to the server should not be “mounted” into the poco the View is bound to. Instead use the poco as the abstraction of the view that a controller pushes up into.

      On the flip side if you are not in SL and are doing MVVM in WPF fat client with ORM then the “remoting and dispatching” plumbing may not be a barrier to working directly with the model. Then the bindings can “pull through” the Model through the ViewModel to update the View. Regular commands going down then don’t need much plumbing and you can move your Use Case service Mediation logic into your ViewModel without the headaches of SL event dispatching to the server and the callbacks. 

  • David

    Interesting article. I also tend to keep data retrieval (and associated error handling) logic outside of my ViewModel, but instead I have that logic in my Commands.

    For example, I would have a GetDataXCommand that takes care of getting data X from the model and returning it (I use a custom command class that notifies listeners of a result when complete), and I expose an instance of that command (via IoC container) as a property of my ViewModel. Unlike the pattern you described I still have to take action within my ViewModel on that data to update the appropriate properties in my ViewModel, but that’s pretty light-weight and doesn’t feel wrong to me.

    Anyway thanks for bringing up some good points.

  • http://alsagile.com Stephane Erbrech

    I am very new to silverlight, and I am mostly learning now the different patterns used.
    I am however fairly experience in web development using the MVC framework.
    The pattern you describe Davy seems to match exactly what I have been doing with MVC.

    A service layer, which will retrieve the data and return Models (mostly Data Containers)
    These Services are injected in the controllers
    The controller makes the necessary calls to the different services and create a ViewModel that makes it easy to display the View.

    So to me, your approach really makes sense, and that’s probably the way I would naturally build an application now, but I’m not sure about 1 aspect. The web is stateless, which is the reason why we dont interact with the ViewModel, but rather with the Controller which will returns us a brand new version of it.
    But Silverlight or WPF, on the other hand is stateful. You do want to leverage 2 ways databinding, It is convenient that the View can talk to the ViewModel, which in turns will trigger some events.
    Probably I don’t see the whole picture of the problem, but I like the clean demonstration from Pedro. If the code is easy to read, easy to understand, easy to test. Well, to me that looks very much like easy to maintain… And that’s what we are after.

    Now I am very eager to see your code examples to understand better how all those components are wired up.

  • mgd

    Can’t say i agree with much of this.

    First, I don’t understand why you say that databinding is part of the responsibility of the VM. The reason MVVM works with WPF/SL so well, is that databinding is handled by the framework. It’s kind of like having a class thats serializable and saying that serialization is on of it’s responsibilities.

    “In most cases, raising those events is very straightforward, but in more complex controls you might need a bit of additional logic to determine which event should be raised at what point”. You have a class and it raises events based on it’s internal logic. Why is this a problem?

    I also don’t understand why it’s a problem that the VM has to handle of exceptions from the Model. Let’s say I have a VM for an email client. Don’t I want to let the user know that an error occurred sending their message?

    If I put a layer (or ten) of mediation between my V and VM you still don’t avoid this problem. Right?

    Finally when you say the MVP(resenter) is a cleaner pattern because the Presenter’s job is “making data (from the Model) available so it can be displayed”, not only do I think this is a bad description of what the presenter does, but it does precisely the two things you say the VM shouldn’t do.

  • http://davybrion.com Davy Brion

    @Mgd

    “First, I don’t understand why you say that databinding is part of the responsibility of the VM. The reason MVVM works with WPF/SL so well, is that databinding is handled by the framework. It’s kind of like having a class thats serializable and saying that serialization is on of it’s responsibilities. ”

    i didn’t say that databinding was something you need to do manually. When i say: ‘facilitate databinding’ then i certainly don’t mean manually putting all of the data in each control.

    “You have a class and it raises events based on it’s internal logic. Why is this a problem?”

    if that’s all it does, then there is no problem

    “I also don’t understand why it’s a problem that the VM has to handle of exceptions from the Model.”

    if it’s doing a bunch of other stuff as well, then there certainly is a problem with it. once again, classes that do too much are usually a bad thing

    “Let’s say I have a VM for an email client. Don’t I want to let the user know that an error occurred sending their message? ”

    did i in any way suggest that exceptions from the model should be ignored just because i said the VM shouldn’t handle those? I said that doesn’t belong in the VM, that’s not the same as saying that they should just be ignored.

    “If I put a layer (or ten) of mediation between my V and VM you still don’t avoid this problem. Right?”

    i dunno… why do you not mind putting a layer (or ten) of mediation between your View and say… the database?

    “Finally when you say the MVP(resenter) is a cleaner pattern because the Presenter’s job is “making data (from the Model) available so it can be displayed”, not only do I think this is a bad description of what the presenter does, but it does precisely the two things you say the VM shouldn’t do.”

    exactly, because the _VIEW_Model should focus on making things easier for the VIEW (ie: facilitate databinding) and that’s not what the Presenter would do

    did you interpret my post as saying that the Presenter should do everything that you’re currently doing in the ViewModel? That’s not what it’s about but your comment seems to suggest that it is

    just for the record, i’d like to know what kind of stuff you _don’t_ put in the VM…

  • mgd

    1) I didn’t say manual databinding either. But how does the word \facilitate\ change anything? Databinding is NOT a responsibility of the view model class, any more than serializing is responsibilty of class that’s ISerializable, or enumerating is to a class that’s IEnumerable.

    2) \if that’s all it does, then there is no problem\. Then we’re agreed; there’s no problem. Glad you changed your mind about this.

    3)Regarding exception-handling in the VM– by your logic any class that handles exceptions is doing too much. Logging? Resource cleanup? Again, I think you are abusing the notion of Separation of Concerns. They shouldn’t be handled in the VM, but not ignored either. Still don’t understand.

    4) The reason I think database access and and the view model should be decoupled from each other can be approached in various ways. On the most general level, I would say that it’s hard to concieve of how you would achieve testability and extensibility without such a decoupling.

    5) You have to explain to me the difference between \making data (from the Model) available so it can be displayed” and \ facilitates databinding\. If my comment suggests that I think your post is saying that the Presenter should do what a VM does, it is because that is in fact what your post says.

    6)The viewmodel is an extremely simple concept. It’s the repository for the data and commands that are exposed to the view. Sometimes it needs access to external services to get that data. Sometimes it needs to perform operations via those services. So my VM would contain references to the data and services needed to do that.

    To claim that the MVVM pattern is \better\ than the MVC pattern would be idiotic. That’s like saying philips-head screwdrivers are better than wrenches. The MVVM pattern has it’s limitations, and I frequently get frustrated those who look at as if it were a religious institution where code-behind is the cardinal sin. But your objections to it are pretty confused.