Problems and Solutions with Model-View-ViewModel

My MSDN article on the MVVM design pattern is finally available!
http://msdn.microsoft.com/en-us/magazine/ff798279.aspx

Unfortunately, Figure 1 is not correct;  we’re working on getting that fixed in the article, but in the meantime here’s a corrected version:

  • The WPF Utilities component should not depend on any unit tests
  • The unit test components should not depend on any other unit testing component
  • The domain model should NOT depend on the data access layer.  Instead, the data access layer should depend on the domain model.  The domain model is the core of everything.  Achieving this is not easy, and I’ll post about how to achieve it.

Let me know what you think of the article!

Robert

10 thoughts on “Problems and Solutions with Model-View-ViewModel”

  1. This was originally posted on my “About” page – I’m moving it here:

    Hi Robert,
    Thank you for your excellent article in MSDN Magazine about MVVM design pattern for WPF/Silverlight.

    I have a follow up question. I noticed that Silverlight 4 natively only support Command for ButtonBase controls. Then, I noticed that there is InvokeCommandAction, CallMethodAction through Interaction.Triggers in the Blend’s Interactivity Assembly which allows you to call methods from View’s XAML.

    I’m wondering what is difference between the native command in Silverlight core runtime vs. these features from Blend 4’s Interactivity Assembly… Would it be equally good to use (InvokeCommandAction, CallMethodAction ) to implement the pure MVVM design pattern?

    1. I haven’t forgotten this – but I have just returned from vacation on a remote island, where I learned how to kneeboard and picked up an ear infection from snorkeling…

    2. I haven’t actually used Blend’s Interactivity Assembly (Until this year I only purchased MSDN Professional, so I didn’t even have Blend).

      You are right that the Command support in Silverlight is still very limited, and I assume this is because the Silverlight team is (working very hard and) churning out releases very quickly. I expect that they will have more comprehensive Command support in future versions (hopefully the next one!)

      So that at this point in time (after doing some reading up on this) it seems that the Blend approach is more powerful simply because it can be applied in far more places. However, that power seems to come at a cost: for one, I do not know how many Silverlight/WPF developers will know about this functionality or be familiar with it. This makes maintaining code written to use this functionality more difficult; especially as understanding it requires knowledge of several other Blend/Silverlight concepts. Additionally, from the samples I’m seeing on the ‘net, the XAML mark-up is considerably more involved using the Blend 4 approach than the typical built-in commanding approach (which makes sense).

      Given the choice, I almost always prefer to use a built-in framework feature that meets my needs rather than a “third-party” add-on (admittedly Microsoft in this case :-). I’m not sure how big the assembly is, but it does increase the size of your download.

      However if you have developers that understand the Blend 4 approach (better than I do!) and it empowers your designers to achieve things not otherwise achievable, then by all means use it. 🙂

  2. Along the lines of the prior question, I would love to see a similar code sample for Silverlight. Great article!

  3. Hi Robert,

    The article was very interesting for me to read, because it had a lot of approaches and tricks I did not use before, and it is nice to see new ideas (for example dynamic properties)

    However there are a lot of problems which I identified with the approaches you describe.

    First of all approach to notifying properties from BOs (Business Objects) is not consistent.
    If you propose BOs to raise notification events for collections – it is logical, expected to BOs also raise notifications for PropertyChanged.
    I like consistency – and I will never agree to have one part of app (BOs) do some work for helping UI, and other part (VMs) to do another (work for UI).

    Second problem with dynamic properties approach.
    I agree it is not maintainable to have Bindings in XAML markup which points to non-existing properties. We should not use bindings at all ! Those should be string properties on some controls:

    When opposed to this we use bindings:

    This is miss leading as there is no property FirstName on VM.

    I understand we have new stuff in form of dynamic objects in C# 4.0, but I don’t agree we have to intensively use it in applications – it can be used in specific areas to do reflection work faster.

    Other problem with dynamic aproach is – you propose that VMs (ViewModels) have to inherit dynamic class – that is big big constraint! ViewModels normally inherit some other things – sometimes hey inherit DependencyObject sometimes other important class. Anyway even if VMs don’t need to inherit other class – forcing to inherit it something is not good up to me.

    I am still familiarising with remainder of article – as View Adapter approach is new to me.

    Thanks,
    Kirill

    1. Thanks for the feedback Krill!

      To address your first comment: I believe you are suggesting that you dislike business objects with INotifyCollectionChanged collections that do not also implement INotifyPropertyChanged. I agree with you, and would strongly suggest that a domain logic layer should either to do both or do neither. Using only notifying collections and not having the business objects also raise property-changed events seems very inelegant. I certainly was not trying to suggest doing that in the article.

      My preferred approach is to use Aspect Oriented Programming (http://www.sharpcrafters.com/) to automatically inject the implementation of the INotifyPropertyChanged interface into the business objects in the domain logic layer. This means that they implement the interface and provide this handy functionality without actually requiring lots of extra and repetitious additional coding. The dynamic property approach I suggest in the article is still highly useful to maintain the complete separation of the view from the model, as well as injecting additional functionality such as undo. Additionally, a ViewModel is still often required to support the view with view-specific functionality.

      As to your second comment: I think it is important to understand the possible trade-offs. Personally, I don’t think that maintaining hundreds of standard proxy-properties is very maintainable either. I think that writing a single class to automatically proxy any simple property access (that is required by the view) is an elegant solution that clearly needs to be well documented and communicated to the development team.

      Unfortunately I think WordPress has lost some of your comment so it is hard for me to comment on your particulars.

      I agree with you that the addition of a new feature is not a reason to use it intensively. However, I own a very small software development company, and if a new feature can help me eliminate thousands of lines of code – or even better, help me not write thousands of lines of code in the first place – then I will certainly take advantage of that feature. Certainly large enterprises will probably not/never jump on my dynamic-property suggestion. However, small development shops might find it incredibly useful. I use Aspect Oriented Programming extensively in my business’s application for exactly the same reason: it allows me to provide my customers with amazing functionality while writing, debugging and maintaining very little code. Anything I can do that elegantly reduces the amount of code I need to write is a big help.

      Finally, to your third comment: Personally, I would strongly recommend that your view-model instances do NOT extend DependencyObject. I have tried this in the past and always found it led to a poorer quality view-model layer. Additionally, the DependencyObject class inherits from System.Windows.Threading.DispatcherObject, which is powerful functionality that you may or may not want to have in your view-model. This alone should make you pause before extending DependencyObject in the view-model; consider that your view-model class could easily be called by event handlers from the domain model running on background threads! Thus, I believe inheriting your view-model class from DependencyObject injects too much of the WPF/XAML view layer paradigm into the view-model layer, and causes implicit (or sometimes very explicit) dependencies on the View layer and view technology. Ideally the ViewModel would still be reusable even if we decided to build a classic Windows Forms view overtop of it (perhaps for a mobile application).

      However, it is certainly fair to say that you don’t want to constrain your ViewModel class’s selection of a base class. Each class only gets one base class, and so the choice of base class should always be carefully considered. Nevertheless, I find that the Layer Supertype design pattern is very powerful and provides a wonderful way of easily extending the entire ViewModel layer with new functionality/capabilities in the future. I also use the Layer Supertype design pattern in the domain model as well, although usually there is a much richer inheritance hierarchy there.

      1. Thanks Robert for detailed answer,
        All answers are very interesting to me,
        I agree with most of your points.

        Regarding DependencyObject – will take into account your warning. Actually I develop few software products, one extends DO, another not. After your comment I consider to remove it as actually it does nothing valuable.

        What is your view about using Dispatcher in ViewModel?
        DispatcherTimer?
        If we are using one of them – can we say we use too much of WPF view layer paradigm in VM?

        AOP – really interesting pattern, I watched some screen casts some time ago, but I try to avoid “magic” in the code. But if the magic can be supported, I will reconsider this – I just need a time/practice to decide that for me.

        Another problem I really see – as you mentioned – is supporting thousands lines of boilerplate code. I agree this needs to be solved. I solved it another way. I expose “real” BOs in VM properties. BOs don’t raise for me property change notifications but they raise some custom property change events – BOs are CSLA BOs. I wrote a set of controls allowing me to access any property on BO from XAML, some controls are invisible – and just operate with property values and do the work of listening to BO changes, and pushing values to BOs; others are visible like TextField, ComboBoxField, SearchComboField, RepeaterField, CheckBoxField, TemplateField, UniField etc..
        But I understand that I am lucky that CSLA has custom event notifications.

        What I still don’t like with dynamic approach is.
        There is no chance of catching the moment when BO changes properties itself. Suppose we change one property on BO, and BO itself will change another property.

        Now if we define that in VM – that will be failure of VM – this is business logic and it should be places in BO. VM has just to listen to BO state and should not know what BO will change when we set some property to it.

        So from the above I can conclude: There is no way dynamic properties can solve problem of UI listening to BOs. The only way is BOs actually raising some kind of events – it does not matter – will it be INotifyPropertyChanged or other one. But without that we have to do “hacks” that ruin architecture.

        And lastly many thanks for pointer to “Layer Supertype” will definitely look into this, sounds very interesting.

        Thanks for interesting discussion,
        Kirill

  4. Hi Robert,

    I just end to read and analyze (or at least I think so;)) your article at MSDN and must said that was very helpful to my newbie and confused mind 😉

    And as any newbie, I think to have different (and why not, better) ideas about the “Document Manager Adapter” approach or to better say, about the problem that you try to solve with the “Document Manager Adapter”. May be I’m just saying crap, so pls don’t hesitate to critic my ideas at point to call me stupid, in fact, will be an honor to me that a design pattern guru like you reply at least this comment.

    So, here we go:

    1- “write a ViewModel singleton that provides the main ViewModel objects from which the View can easily retrieve all other ViewModel objects as required.” have for me seriously consequence in code organization/maintenance cos as ViewModels are added/removed form the application, the singleton ViewModel must be updated too and programmers can’t have a simple relation between a ViewModel and its corresponded View anymore. Beside, I see problems in separation of concerns too, pushing the responsibility inside the singleton ViewModel to keep updated the inventory of application’s ViewModels don’t see for me a thing that fit inside a ViewModel.

    2- I think that “in the ViewModel layer … think in terms of documents” is a mistake, cos you are carrying a purely View concept to the ViewModel layer.

    My idea is that if we split the “semantic of the UI” (I’m thinking here in things like “center View”, “detailed View”, “actives Views”, etc.) from the “UI appearance” (tabbed document, node tree, movable screen placeholders, or whatever form designers give to an “UI semantic component”) we get in a better position. With such approach, we can get a singleton ViewModel that have an inventory of named FrameworkElements, where each FrameworkElement is related with one or more “UI semantic components”. Interesting things can be done with this way to organize the code, for example, we can cache the Views (with its corresponded ViewModel) after we rendered it. Other useful thing is that after we define the “semantic of the UI” and the “navigation state machine” (with this I’m referring to the possible stated of the “semantic UI” and the ways to change from one state to another), designers – programmers interaction decrease considerably.

    To clarification: we can define as part of the “semantic of the UI”, that when one “UI semantic components” (for example “detailed View”) is fill (assigned to an FrameworkElement) , another “UI semantic components” (for example the “footer View” disappear, get null), may the example don’t have much sense but expect you get the point. Beside, the transition between the state are exposed as ICommands inside the ShellViewModel or to what you call the singleton ViewModel.

    Take a look at http://compositewpf.codeplex.com/discussions/247687, there I write more about this.

    Cheers
    Frank Abel

Leave a Reply

Your email address will not be published. Required fields are marked *