Which came first, the View or the Model?

Architecture

As I wrote and subsequently taught the Silverlight Tour workshop, I've had a number of discussions with students, clients and the community-at-large about how to architect Silverlight applications.

The momentum behind the Model-View-ViewModel (MVVM) design pattern makes a lot of sense to me, especially with declarative views (as seen in Silverlight and WPF). Most of my thinking around this was covered in my MSDN article about it:

http://tinyurl.com/slmvvm

One topic that the article is thin on is how the View and the ViewModel are related. After the article shipped, I had some lengthy conversations with lots of people about this from John Papa, Laurent Bugnion, Glenn Block, et al. It occurred to me that some of the nomenclature was confusing.  The three parts of the MVVM are:

  • Model: Responsibile for managing and delivering data.
  • ViewModel: Responsible for shaping, sorting and filtering data for a view(s).
  • View: Responsible for formatting and displaying data.

The three elements have a clear separation of responsibilities. Typically a small number (or one) model exists in my projects with Views and ViewModels being built in pairs.  Though it is not uncommon to build more than one view for a single ViewModel. As long as the separation is there, having two views that show the same data but in very different ways is in keeping with the pattern in my opinion. This can be seen in this simple illustration:

Model-View-ViewModel

Most what I've mentioned in the article and so far in this blog post is what most of the community seems to agree on. The last part of the contention is how do you create Views and ViewModels.  The two approaches I hear most often are:

  • View-First: The View has a relationship to its ViewModel(usually through data binding).
  • ViewModel-First: The ViewModel creates the view (usually through an IoC container).

In View-First, it is usually is exemplified in XAML like so (as I showed in my article):

<UserControl x:Class="MVVM.Client.Views.GameView"
             ...
             xmlns:data="clr-namespace:MVVM.Client.Data;assembly=MVVM.Client.Data">
  <UserControl.Resources>
    <data:GamesViewModel x:Key="TheViewModel" />
  </UserControl.Resources>
  <Grid DataContext="{Binding Path=Games, 
                      Source={StaticResource TheViewModel}}">
  ...
  </Grid>
</UserControl>

 

In ViewModel-First, it is usually implemented using a Inversion of Control container (e.g. Unity, Ninject, Spring, etc.). This way the ViewModel can request the interface (in the constructor) for the View it expects:

public MyViewModel
{
  public MyViewModel(IMyView view)
  {
  }
}

 

In both of these methods I tend not to like the sticky-ness of the view to the view-model. Also, both of these imply a one-to-one relationship which while the common case, is not the always case.

I have come up with another pattern that I am tentatively calling a "Marriage".  (I don't love this name but its the closest, non-technobabble name I've found for it).

Marrying the View and ViewModel

In my design, I want the View and the ViewModel to be ignorant of each other so that I could mock either side of the equation without impacting the other. In practice, mocking the View-Model is common, but mocking (and testing) the View is not common at all.  But by not tying them tightly, it does allow us to move to a one View-Model to multiple Views without any real pain.

In a Marriage, you would simply apply the ViewModel to the View at runtime. This may be done with a class that handles and isolated this or simply with some simple code.  For example, I typically have an IView interface that requires a method to do this applicaiton like so:

public interface IView
{
  void ApplyViewModel(object viewModel);
}

 

Then in the module declaration for a module (or assembly) holding the View and ViewModel, I simply use the IoC container to create them (either using Interfaces or class names depending on the complexity of the project) then apply the ViewModel to the View via the interface:

IView view = theContainer.Resolve<IGameView>();
IViewModel vm = theContainer.Resolve<IGameViewModel>();
view.ApplyViewModel(vm);

 

The magic of this code is that you retain the anonymity while perserving the functionality. It becomes the user of the View/ViewModel's responsibility to determine how they are related.

I explain this pattern in my article on the Prism Framework and Silverlight coming in next month's MSDN magazine.  Using this pattern with an overall Composition pattern for building your applications has a number of benefits beyond separation of responsibilities and testing.

Just to throw a plug in as well, I also teach this pattern (and Prism) in our Advanced Silverlight Workshop coming to Seattle in August

Let me know what you think of this versus the View-First or ViewModel-First patterns.

 

Comments

Gravatar

John Papa Saturday, May 23, 2009

Nice post. I like the marriage aspect you wrote about. I prefer to keep my classes ignorant of concrete implementations, too, usually using Unity (or any IoC container). This is a nice way to link the 2 even if you don't need more than a 1-1 pairing of V to VM.

Gravatar

Darrel Miller Saturday, May 23, 2009

What you are doing with your "marriage" code is very similar to what I do. I use a class to encapsulate this "coming together". I also use this class to aggregate additional behaviour objects that manage common interactions between the ViewModel and the View.
In fact I go a step further and move all behaviour out of the ViewModel into the "Marriage" class.
You want to know what I call my Marriage class. A controller. And if you drop the View in ViewModel, you are right back to a MVC triad. Sheer bliss :-)

Gravatar

Shawn Wildermuth Saturday, May 23, 2009

Darrel,

MVC still works well in declarative situations, but I find the pure Controller doesn't make as much sense to move the entire VM there. If you want to do MVC in Silverlight or WPF, there is nothing wrong with that. I just find this model simplier in most cases.

Gravatar

Pavan Podila Saturday, May 23, 2009

Nice post Shawn,
Instead of creating an IView interface I typically do constructor injection of the ViewModel into the View. Using an IOC container like AutoFac makes this automatic.

Gravatar

Shawn Wildermuth Saturday, May 23, 2009

Pavan,

The IView isn't a decorator interface, it actually has a method on it. Instead of using constructor injection (Like ViewModel first above) I like having hte separation so I can marry more than one view if necessary. If you need two views with your situation, you have to change the ViewModel.

Gravatar

Jeremiah Morrill Saturday, May 23, 2009

Very lucid explaination Shawn. I can't wait for your Prism article! Been working with it for a couple months and am eager to compare others' implementation to my own.

Gravatar

James Ashley Saturday, May 23, 2009

Shawn,

This appears to be how Josh Smith glues the view and the viewmodel together in his MSDN article, but without using di. I had assumed that this was the norm rather than the exception.

It certainly makes sense in top level relationships between views and viewmodels. But what would you recommend when a view contains additional views (user controls) and the viewmodel contains additional viewmodels or collections of viewmodels?

It seems to me, in this case, that binding is definitely the easier way to go. Would you encourage manually binding these sub-views to their sub-viewmodels, also?

James

Gravatar

Shawn Wildermuth Saturday, May 23, 2009

James (re: nested views/vm's) I would handle it with data binding though I haven't seen a large case where this is happening so I don't have a lot of evidence that binding will be sufficient. This might be a case where ownership might make more sense, I have to think about it more though.

Gravatar

Nikola Malovic Saturday, May 23, 2009

I totally agree with you regarding the need for generic abstraction of the view.

In my implementation I am relying on the fact that every view has an DataContext property (sadlly not member of any interface) so I am defining
IDataBindableControl<T> where T:ViewModel
{
T ViewModel {set; }
}

So, every view implements that interface (as in your example) as mare {DataContext = value}


Generic form of this interface is there due to the way how I register mappings in Prism bootstrapper.

container.Register<IDataBindableControl<UserViewModel>, UserView>

and the ViewModel is base class every of my model has

Having all this specialized IView and IPresenter in Prism samples is complete overkill IMHO

Gravatar

Shawn Wildermuth Saturday, May 23, 2009

Nikola,

Even though I use Unity, I typically don't bother with the specialized interfaces unless they are necessary to have a code contract. For simple cases, I simply create them like so:

container.Resolve<MyViewModel>();

Which allows me to use constructor injection without having the overhead of creating decorator interfaces. It doesn't give the ability to mock these later, but for simple projects its a good trade off, simplicity versus mocking.

Gravatar

Nikola malovic Saturday, May 23, 2009

Well, I am doing the same container.Resolve<MyViewModel>(); and then ctor DI the view.

The only difference here is that in my implementations View Model lives in separate component then View (judgging by the Twitter - opposite from what you do :)) and thus VM has to be ignorant of the concrete view, so in order to have DI I have to do next things :
1) UserView implements IDataBindableControl<UserViewModel> (interface defined in common infrastructure assembly)
2) In module initializer class (View component) I define the view mapping then
container.Register<IDataBindableControl<UserViewModel>, UserView>
3) In base class ViewModel<T> (inherited by UserViewModel) I have this

protected ViewModel(IDataBindableView<T> dataBindableControl)
{
this.DataBindableControl = dataBindableControl;
this.DataBindableControl.ViewModel =
(T)Convert.ChangeType(this, typeof(T), CultureInfo.InvariantCulture);
}
That’s how when I do the same
container.Resolve<MyViewModel>();
I am getting UserView injected into the UserViewModel without coupling them
I’m going to blog post simplest possible example illustrating the approaches I use in my Prism customization (MVVM is just one thing)

Gravatar

James Ashley Saturday, May 23, 2009

Like Nikola, I'm really curious about how you intend to mock the IView. You don't have a datacontext to work with and I'm not sure how you would mock binding behavior. If you throw events for commands, you can include these in your interface, but then you'd still have to hook up handlers in the ViewModel somehow -- and then you pretty much end up with an MVP pattern.

That would make for a fascinating blog entry. Before your post, I had assumed that this was an unsolvable problem and that the MVVM simply didn't lend itself to mocking the IView.

Gravatar

Shawn Wildermuth Saturday, May 23, 2009

James/Nikola,

That's the idea of using IView instead of DataContext is that I don't need to 'mock' the view's data binding but can make some assumptions in the mocked version of the view to assure that the parts of the VM exist that the View expects. While this is an odd way to test the VM, its plausable. I am still digging into what I think are best practices and hope to do an upcoming testing article to try and clarify that part of my vision. Thanks for your input, it really helps.

Gravatar

Josh Gough Saturday, May 23, 2009

Shawn,
Good article. I've been building a simple dice game in C#. I have built and tested the game logic, now I want to be able to put multiple front-ends on it, and I also want to make it playable with multiple players across the internet.

My initial thought is to create a simple web service, probably done in a restful way, that allows for each game instance to have a unique address and each roll and move to correspond to a URI as well. This will allow it to be played over simple HTTP.

My question is: when building a WPF or Windows Forms UI for it, are there some simple patterns I can follow to decouple the UI from the underlying source of the Game object model?

The first UI I built hosts the game explicitly as a reference to the game assembly. However, there really are only a couple of messages that the UI needs to send to update its game-board display. One is the "Roll" message to get the dice, the other is the "Move" to select a cell.

If I make the UI, the buttons and cells on the gameboard, post a message to a local, in memory "Controller" or "Queue" for lack of a better term, then I can be free to implement the source either in memory or from a remote rest interface.

The difficulty in getting my head around this is thinking of the fact that when player one's turn is over and player 2 must take over, the local client must read messages from the queue or otherwise get notified of changes -- as opposed to having clicks-on-the-board imperatively drive the updating of the underlying model.

I know I'm rambling, but just curious on your thoughts on something like this.

Thank you,
Josh











Gravatar

Shawn Wildermuth Saturday, May 23, 2009

Josh,

In WPF, this MVVM model simply works. In Windows Forms is harder because the data binding story there is a mess.

Gravatar

Glenn Block Saturday, May 23, 2009

Nice post Shawn.

I have to say I am still skeptical on the need to mock the ViewModel, but I am willing to be convinced. As far as mocking the view, for testability etc, this is a very common practice coming back from the MVP days. It's not for testing the view, rather it's for testing the view model.

I am a big fan theoretically :-) of keeping the VM and the view completely divorced at compile time and temporarily married at runtime. However, I worry about the complexity it introduces to keep them separated, particularly in cases where the ViewModel needs to talk back to the view in ways that it can't through databinding. Passing funcs are one option, but then you have a bunch of private delegate scattered throughouot. Jeremy Miller and I have had quite a few discussions on this, and I could say his thinking on this influenced my thinking. What are your thoughts on View talking back to the VM?

Regardless, I've also been thinking along similar lines around the marriage. One idea I've been floating around for some new ViewModel work we are doing is the idea of a ViewFactory which is a simple abstraction for marrying up the two, i.e. you call for a View, and it handles finding the View and VM and wiring them up.

Gravatar

Shawn Wildermuth Saturday, May 23, 2009

Glenn,

I think the VM talks to the V through events or data changes. I stole Laurent Bugion's idea to have a bindable data (e.g. Errors collection) that are bound to the View and changing the collection allows the view to visualize that data like any other. As far as the V talking to the VM, I think that needs to be done with commanding of some sort (not necessarily ICommand based) like DelegateCommand in Prism or Behaviors. Once Blend reaches RC, I have a ExecuteBoundMethodBehavior that I will be adding to the SilverlightContrib project that allows that behavior (pun intended).

Gravatar

Glenn Block Saturday, May 23, 2009

Adding on to my previous comment, the point of the factory would be to provide a centralized way of getting the View without any concern of how it is created. You can do this today with an IoC container, however the point here would be to provide a generic hook in the framework, that our libraries could call without being bound to a specific implementation. It's analagous to some of the work done in MVC.

Gravatar

Glenn Block Saturday, May 23, 2009

The event route is possible, I am just not a fan of it. As far as using Data, you can only go so far. Data works for simple visualization of lists. This is where the IView approach plays nicely as it gives me a nice discoverable method that I can call. The IView doesn't necessarily bind me to a specific view, just that the view implements a specific interface.

Gravatar

Borek Saturday, May 23, 2009

Hi Shawn,

I am confused about what you said in this line: "In practice, mocking the View-Model is common, but mocking (and testing) the View is not common at all."

My understanding is that when you mock the View, you do so to enable testing of the ViewModel. So mocking Views is in fact very common.

Other than that, I like you "Marriage" pattern. Makes a lot of sense.

Gravatar

Ivan Shumilin Sunday, May 24, 2009

I think this is Model-ModelView-View pattern.
ModelView much closer to the Model and potentialy has many Views. Original VM (in M-V-VM) is a statefull representation of View and coupled with it in many cases.

Gravatar

hh Tuesday, May 26, 2009

I have three modules ModuleA,moduleB and moduleC.My approach is similar to what you followed i.e., coupling the view and viewmodel at runtime.My problem is i have moduleA which publishes an event through EventAggregator now moduleB has to subscribe to this event as my viewmodel of moduleB is Generic i.e.,it is designed to serve moduleC also i dont want the viewmodel of moduleB to subscribe to this event.so which one should subscribe to this event ?

Gravatar

Colin Blair Wednesday, May 27, 2009

My code generally looks like this:
public FooView : IView<Foo>
{
public FooView(IViewModel<Foo> viewModel)
{
this.DataContext = viewModel;
}
}
I guess that is technically View-First but I use constructor injection to get the ViewModel set instead of hard coding it like your example shows and I use Prism's IModule to setup the container.

Gravatar

Adam Grocholski Thursday, May 28, 2009

Two questions:

1. I'm not seeing the "Marriage" here. If the View and ViewModel are now ignorant of each other and require a third party (i.e. the user of the View/ViewModel) to determine how they are related, isn't that more of a "Divorce" than a "Marriage"? Of course, since "Divorce" has negative connotations, maybe it's a "Dissociative" pattern.

2. What exactly is going on in an implementation of IView.ApplyViewModel? Are you just setting the DataContext of the View to the object (i.e. ViewModel)?

Gravatar

Adam Grocholski Thursday, May 28, 2009

Two questions:

1. I'm not seeing the "Marriage" here. If the View and ViewModel are now ignorant of each other and require a third party (i.e. the user of the View/ViewModel) to determine how they are related, isn't that more of a "Divorce" than a "Marriage"? Of course, since "Divorce" has negative connotations, maybe it's a "Dissociative" pattern.

2. What exactly is going on in an implementation of IView.ApplyViewModel? Are you just setting the DataContext of the View to the object (i.e. ViewModel)?

Gravatar

shemesh Thursday, June 4, 2009

we've been using the MVVM without even knowing we do (and without knowing its called MVVM).
we've built a complex application and it only seems natural and rational to work this way.

just one difference: our ViewModel is singleton:

private static AdminModel _model;

// Constructor is 'protected'
protected AdminModel()
{
}

/// <summary>
/// Get Instance of the AdminModel
/// </summary>
/// <returns>Instance of AdminModel</returns>
public static AdminModel GetInstance()
{
if (_model == null)
{
_model = new AdminModel();
}
return _model;
}

Gravatar

craig Tuesday, June 23, 2009

mvvm? don't you mean MVP? I'm not sure i see any difference at all?

Gravatar

Josh Gough Tuesday, September 22, 2009

Hey Shawn,
Hope you are doing well. Trying to learn a bit of SL/WPF now. I have gotten around finally to getting a very simple, but functional RESTish game server and client out based on what I posted before. It's at http://apps.ultravioletconsulting.com/Skookzee.

Each game event gets POSTed to the URI for the game-under-play, and then each client GETs the most recent, unseen events to process. The first client there is a simple WinForms client since I already knew winforms.

I'm going to build a jQuery-base in-browser client, and a SilverLight client (hopefully with 3D-ish dice...I purchased 3DPaintBrush and imported a dice model from Google Sketchup...now just have to learn all this stuff!)

thanks,
Josh

Gravatar

Robert Taylor Friday, October 16, 2009

I know I'm a bit late to the party, here, but while you talk about the View and VM what about the Model? The VM binds to both the V and the M so why not 'marry' the Model and VM as well?

If the View is being determined at runtime, i.e. Desktop View vs PDA View, then this pattern seems to be better than the standard one; but you imply that a MV could support multiple Views of the same data in which case shouldn't 'ApplyView' really be 'AddView'?

But generally, I like this pattern.

Gravatar

Shawn Wildermuth Friday, October 16, 2009

Robert,

Typically the VM and the model are married at runtime as well (usually with dependency injection). The only real marriage between them that the separation indicates (IMHO) is about whether you're mocking the model or not. Though there are some edge cases where you could determine the model based on other data (e.g. in the cloud versus in the data center).

Gravatar

Jorge Wednesday, January 27, 2010

Hello Shawn.

I was looking for this kind of solutions for a while and I really like this one you propose. What do you think about the David Hill´s aproach in his blog?

http://blogs.msdn.com/dphill/archive/2009/05/18/viewmodel-and-dependency-injection.aspx

In few words, he think that IoC is not a good idea for marrying de View with the ViewModel.

Thanks in advance for your time.


Leave a Comment

*
*
*