The spirit of MVVM (ViewModel), it’s not a code counting exercise.

<Warning>Long post follows</Warning>

Lately there is a lot of momentum and interesting conversation around Model-View-View-Model. There’s several good resources out there that discuss the basics of the pattern, who the actors are that are involved and what role the play. I’ll let those speak for themselves, including John Gossman’s great post here, Martin Fowler’s post on the more general PresentationModel pattern and more recently Josh Smith’s MSDN article, Rob Eisenberg’s new series, and Ward Bell’s posts which touch on some of the deeper complexities involved.

In many of these discussions (not including the posts I referred to) it seems like one aspect of ViewModel get’s lost, which is “Why use it in the first place?” This leads to a lot of debate around details of implementation including one item in particular which is whether or not code in the code-behind is an anti-pattern. Building off of the stage Phil set in his great LOD post, I’ll say ViewModel is not a code-counting exercise.

The essence and the spirit

John says in his post, “Model/View/ViewModel is a variation of Model/View/Controller (MVC) that is tailored for modern UI development platforms where the View is the responsibility of a designer rather than a classic developer.  The designer is generally a more graphical, artistic focused person, and does less classic coding than a traditional developer.”

Martin then states in this Bliki that “The essence of a Presentation Model is of a fully self-contained class that represents all the data and behavior of the UI window, but without any of the controls used to render that UI on the screen. A view then simply projects the state of the presentation model onto the glass.” Martin then adds “It’s useful for allowing you to test without the UI, support for some form of multiple view and a separation of concerns which may make it easier to develop the user interface.”

From John’s perspective, it is a pattern that enables a UX designer (non-developer) to be responsible for the UI. From Martin’s perspective it’s about separation-of-concerns and testability. So which one is right? I say both. Also notice neither one said anything about having zero-code in the code-behind. Instead they spoke about maintainability.

So what is the spirit of MVVM then? I say it’s building UIs that utilize platform enhancements in WPF and Silverlight to provide good separation between UI and business logic in order to make those UIs easier to maintain by developers and designers.

When I say designer, I don’t mean only the stereotypical guy/gal who wears a black sweater :-). It may also be a developer who is using Blend/Cider to define the UI, which is likely, as we all know hand coding a ton of XAML is anything but fun.

Why have I called out WPF and Silverlight? Because the pattern is specific and solely on the specific data binding, data templates, attached properties and command implementations found in the platform. Presentation Model on the other hand is entirely general and places no such specificity. I would not for example recommend ViewModel as an appropriate pattern for ASP.NET or Winforms, but I would however recommend PresentationModel, in addition to MVP, etc.

It’s not about counting code

They key here (and which I want to touch on) is the last part, “easier to maintain by developers and designers.”. This means (if you buy my definition) that the chosen implementation should consider both aspects of the equation, that is what does it do for the developer and what does it do for the designer. Obviously tradeoffs have to be made, but the key is finding a healthy balance, reducing the negative impact to both.

Which brings us to the code counting question. Does having zero code in the code-behind make the UI easier to maintain? I say it depends on what kind of code you are talking about:

If the code is UI level business logic which does not relate directly to the rendering of the view, such as determining whether or not certain elements are visible, or enabled, then I agree, this kind of code is a separate concern and should not appear in the View at all and be within the ViewModel. I would include in this the XAML, as the XAML is still part of the view. Why shouldn’t this logic be there? Because it makes the UI difficult to maintain by creating a tight coupling between the UI and the logic. It makes it difficult to test, and is also very brittle and likely to break as the UI evolves in response to changing requirements.

On the other side of the coin are UI-specific concerns, I would include in this setting enabled state, visibility or starting/stopping animations as well as even logic that relates to which model data a specific UI element binds to. That may sound contradictory to my previous statement but it is not. What I mean is, the ViewModel should contain the logic to determine whether something is visible or not, and the View should act on that knowledge to then hide the element. Adding this logic to the ViewModel would introduce tight coupling between the ViewModel and the View, this time from the ViewModel side.

Now being that it is a UI specific concern, the next question is how should it be handled, as code in the code-behind or in XAML? And for that answer I would say it depends on the specific concern itself, as well as whether or not there is a UX designer who handles the UI. Even still,  I would look at an approach that best meets the needs of both developers and designers.

Data binding

Let’s take data binding as an example. If I am working with a dedicated UX designer then bindings in XAML is the prevalent technique that our tooling provides for data binding. Now it does negatively impact the development team to some degree in that due to XAML’s very loose nature it is very easy to break and difficult to verify and test. However there’s no other option for the designer other than forcing them to write code, which is how should we say less than optimal.

If there was no UX designer present however, I would see no issue with putting that binding definition in code, even in the code-behind. As developers are used to writing code, not markup, and the developer IDE provides much richer support for developers in code. Now that being said, the API for defining bindings is not really well-suited for doing them in code, but OSS solutions like “Fluent Silverlight” help bridge that gap.

Animations

A different example relates to animations. The user clicks a Save button on the Edit Order screen which requires some UI cue to the user such as an hourglass while the order is saving, and another cue once the Order has saved. The question is where should this logic live? In the XAML or in the code? You could handle this in the XAML by using triggers, attached behaviors and the like. In the case of Silverlight, you don’t yet have triggers yet baked in, but you could look to using those included with Blend.

Now although you “could”, I wouldn’t, though you might feel different. The reason goes back to maintainability, having such logic in the view means once again it is easy to break and difficult to test (How do I know it actually works?). Instead, I would opt in this case to separate into two parts, the pure visual part and the logic. The pure visual would be the hour glass animation, and the saved completed screen which could likely be purely defined in XAML. However, the logic part which determines to show the hour glass while saving is in progress would rest in the code. I would achieve this by adding OnSave,OnSaveCompleted methods to the view which would both contain the logic to actually display the elements.

The ViewModel would get injected with either an interface to the view, or with a set of delegates it could call to once save begins and completes. Yes, I did say I’d put code in the code-behind! That is ok because it is code that relates entirely to a view-level concern. Also I would argue that putting the one line of code in the View, only minimally impacts the designer. They can still verify that the animations works. On the plus side it means that we’re remove one more potential piece of brittle, un-testable logic. Also it improves debugging as a developer can put a break-point on the view methods to and see whether or not they are even getting called, additionally it ensures that an exception is thrown if the animation in question is removed.

Commands and Parameters

The last thing I want to touch on relates to invoking commands, and usage of command parameters through element binding, vs using bound properties on the ViewModel. The user selects an item in the Order list, and double clicks. Do we a) Use element binding and have clicking on the “Open Order” button invoke the OpenOrder command passing in the currently selected order as a parameter, or b) Set the orders list selected item to bind to a SelectedOrder ViewModel property and then have a parameterless OpenOrder command which uses the SelectedOrder order property on the VM itself.

I would argue B over A, and why relates back to the maintainability question. If I use element binding, again I make the view harder to maintain. In this case, I haven’t coupled it to the VM, but I have coupled one part of the View to another part of the View. The impact here is on future refactorings of the View. If move around elements in the view such that the relative binding is broken, I broke my UI, if I use the second approach however, I can re-factor / replace elements all day long without breaking any relative bindings.

Yes, I’ve added properties to the ViewModel, but those properties are easy to discover, and result in UIs that are less prone to break over time. I should also add that using approach B works just as well for a designer, as they can easily bind to the properties on the VM for the parameters and parameterless commands.

Conclusion

In conclusion, the spirit of MVVM is about producing maintainable UIs for the developer and the designer, not UIs that have zero code. I would recommend folks who are developing using the MVVM pattern to focus less on whether or not there is code in the code behind, and rather focus on the type of code and whether it improves / or hinders the maintainability of the UI. Sometimes having a bit of code in the code behind actually goes a long way toward improving it.

What are your thoughts on this topic? I’d love to hear them.

This entry was posted in MVVM, ViewModel. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • jcdickinson

    You touched on blend briefly. Problem with blend is that it is UI driven. We have a few XAML dudes here and the more savvy guys’ XAML always wins in terms of rendering performance. More savvy also equals more maintainable. At the same time, more UX experience with developers means that said savvy UX guys work faster, and write better markup.

    In other words to have effective MVVM both parties need to have blurred interest lines.

  • Steve M

    Late comment here – but I agree 100% with Glenn on all points.

    One question I wanted to put on the table is regarding the whole ICommand thing on a view model.

    What if in response to a button click, we need to open another window? If the button is bound to a command in my view model – a stand alone, testable assembly, I have a problem.

    The view model assembly is seperate, cannot open a window, and in fact should not know about windows, correct? Trying to open a window from the view model just does not feel right anyway.

    In the end I like classic WPF commands, along side classic event handlers directly in the code behind. All these handlers should be a *very thin* path to the VM. Eliminate as much code from the codebehind – absolutely – but not all of it.

    Incedentally, sometimes you just have to use event handlers. We use Infragistics, and when a user double clicks a row in a grid, there is no ‘command’ available for this.

    In the case regarding the ICommand ( which I do not like ) I think instead a classic WPF command should be used. The handler should ask the VM as to whether an entity should be edited. The classic WPF command handler in turn should open the next window. Can’t do this easily in the case mentioned above.

    The view models make business decisions ( can edit ) and the view handles display specifics ( new window, show hidden element, whatever ). Whether something is accessible in the business model could translate to whether it is visible or disabled in the view.

    So after all of that, why do we need ICommand?
    Perhaps my perspective is wrong. Maybe the ICommand could raise an event, and the view could respond by opening a new window?

  • http://goblincave.net Magnus Lund

    I agree mostly with you on your points – it is not until recently I finally gave into ModelViews.

    One thing, I still like to keep in XAML is value-converters. I know many swear to having most if not all properties be of type string on the ViewModelView and then handle conversion in the ViewModel. However, I like the maintainability of global resourcedictionaries and having the binding be somewhat more complex. For me it is easier to maintain my bindings than maintaining all the properties in the ViewModel.

    Another thing, I keep in my code-behind is handling drag and drop events. The ViewModel delivers actions to be performed when the correct events trigger – this is mostly from having only one action passed from the ViewModel to handle a number of hook-in points of the UI (be it keybindings, mousebindings or eventbindings).

    Oh, and another point about commands is that we use our own implementation of ICommands and have them directly called in XAML, as they must be available in globally available context-menus, menus and toolbars.

    Of course, there is another variable – this mode of work works for us because we have no dedicated designer.

    But certainly we agree that the less code in the code-behind -> less maintenance.

  • http://vbandi.dotneteers.net András Velvárt

    Glenn, this is very interesting and thought provoking. There is one issue with parameterless commands though. Consider a list of items in Silverlight or WPF, listed in an ItemsControl (not a ListBox). The ItemsControl does not have a SelectedItem property, so how will the VM differentiate between the items that the user has clicked on? I am considering that we should allow the DataContext of the item to be passed along with the command. DataContext should be a ViewModel or Model object anyway, so the integrity of the VM is not harmed.

    Love the captcha btw. :)

  • http://codebetter.com/members/gblock/default.aspx Glenn Block

    Thanks Neil, that is good feedback which I will forward on to the Blend team.

    I agree that there needs to be better tooling support both in Blend and our developer tools.

  • http://neilmosafi.blogspot.com Neil Mosafi

    I think until designers (e.g. Blend. Cider, etc) have explicit support for the MVVM architecture, it’s going to be hard to get the proper designer/developer workflow going that is so often espoused by MS etc.

    We need Blend to have a feature like “create a view from a view model” that lists all the view models in the application and allows views to be created for them. The designer gets to see all the properties and commands on the view model and can easily create UI elements which bind to those.

    In short, if the pattern were explicitly acknowledged as the preferred way of doing things, it would help immensely. Currently it’s just baked on top of the existing framework, and is often implemented slightly differently in each application it’s used in!

  • http://codebetter.com/members/gblock/default.aspx Glenn Block

    Hi Laurent, my example my not have been a good one. I was trying to give an example that involves using releative binding to grab the parameter.

  • Steve Py

    I’m no expert on VM or even MVP though the common theme is separation of responsibility, and it seems that the differences just boils down to semantics or pedantics.

    I hate seeing any kind of business logic in the UI. To that effect, I’d say the best frame of mind to be in when considering patterns for UI, whether MVP, MVC, or MVVM is to try your hardest to ensure that there are no conditional statements involving domain objects, or even involving parameters in your code-behind.

    UI code should signal a controller, or presenter, or ViewModel, whatever you want to call it, with the actions taken by the user. The controller does it’s mojo, then tells the view to refresh with a specific state. UI renders and interacts, and does nothing else.

  • http://popcode.com Ed McPadden

    Great Post Glenn.

    I am working on a Silverlight app that is written using Prism. I use the MVVM pattern throughout. But I do find occassions where I need to work in the code behind to perform some very view specific functionality that would be very akward to push back into the VM.

    There are also times where I am using 3rd party controls that don’t do a good job at being compatible with the MVVM pattern. In these caes, it is just easier and more maintainable to handle events from these controls in the code behind and in the code behind call back into the VM when appropriate.

    While I’d rather keep as much as I can out of the code behind … but I don’t think it needs to be done at the cost of being overly complex when the code addresses view specific concerns.

    Thanks Glenn for this insightful post.

    …Ed

  • http://kentb.blogspot.com Kent Boogaart

    Fantastic post, Glenn.

    > The ViewModel would get injected with either an interface to the view, or with a set of delegates it could call to once save begins and completes

    Can it not just maintain a state machine? For example, it could expose a property called State that changes between Idle, Saving, Saved and back to Idle. The VM updates this property as necessary and the view just binds to it and uses it as a trigger for animations. This just seems simpler to me than having the VM explicitly call back into the view.

    > Yes, I’ve added properties to the ViewModel, but those properties are easy to discover, and result in UIs that are less prone to break over time.

    Those properties are also there to *model the view*. If the view exposes selection, then why shouldn’t that selection be manifested in the view model? Doing so allows my unit tests to easily and naturally imitate users selecting an item. To that end, I would have a SelectedOrder property on my VM, just as you recommend.

    @Ward: it is possible to factor out a lot of repetition in SL XAML to attached behaviors. To take your example, you could do something like:

    The attached behavior then goes off and creates the Binding object as appropriate and assigns it to the TextBox.Text property. You’re limited only by your imagination here.

    What’s not clear to me is how well this works in practice with designers. That is, would the designer know how to apply the attached behavior? Would they want to? Is it more effort for them to set the attached behavior than it is to re-configure the binding every time?

  • http://devlicious.com/members/bennage/default.aspx Christopher Bennage

    @Glenn, Wow, you took the words right out of my mouth with this post. I missed most of the weekend tweets about this, but the the question of “Why use VM?” and your answer are mine exactly.

    @Ward, I agree with you as well. Convention-based XAML is something I think more and more about all the time. It’s a little reminiscent of the strongly typed UI helpers in MVC. I’m sure that if you give Rob 24 hours, he’ll have it up and running in Caliburn.

    @Clint, if I can be selfish, check out our book:
    http://www.amazon.com/Sams-Teach-Yourself-WPF-Hours/dp/0672329859
    It’s an intro to WPF but we talk about this style of development as well, though the concepts have matured a great deal since it was published.

  • http://www.acceptedeclectic.com pete w

    Ive been using MVVM for a few years now, and I have a love/hate relationship with the pattern.

    I love it for its reliability. No matter how simple nor complex the UI may be, I can depend on successful results by following some simple rules. Heck I even use ViewModels in ASP.NET MVC!

    I dont like it for the same reason as many other detractors claim it is redundant, violating DRY etc. As programmers, we tend to not be satisfied with a solution until it is elegant and succinct, and MVVM is neither.

    Maybe once C# 4 rolls around we can revisit the debate and come up with something more elegant but in the meantime, I’ll make peace with cranking out some more ViewModels :)

  • http://www.thejoyofcode.com/ Josh Twist

    Great post Glenn – I think you’ve nailed the ‘when it’s OK to code-behind’ question here.

    You should have called this post ‘the spirit of MVVM’ or something as you’ve really capture it here :)

    Just of other comment readers – there was a discussion on Rocky Lhotkas blog about this recently: http://www.lhotka.net/weblog/CommentView,guid,e550e8f1-9d50-41ed-8ffe-ef87a11f90f6.aspx#commentstart

  • http://wekempf.spaces.live.com wekempf

    I agree with most of this post. I don’t think the knowledgeable folks have said that “no codebehind” was a goal of MVVM, but I can see how things that even I’ve said myself could be misunderstood . I advocate no codebehind, not as a goal of MVVM, but as a goal of making the View as “designer only” as possible. Many designers wouldn’t have a clue how to modify the codebehind, and I’d prefer that designers and developers not have to work so closely together that codebehind magic would be necessary. These are distinct things, though. MVVM helps to eliminate codebehind, but it’s not the only thing necessary to accomplish that goal (things like value converters, markup extensions and behaviors are required as well), nor does MVVM concern itself with codebehind. We (those of us who want to eliminate most codebehind) probably do need to make this clearer in our discussions.

    Ward’s convention idea is doable today. Walking the tree is easy, and so creating bindings based on conventions should be relatively easy as well. It wouldn’t even require codebehind to accomplish this. I think this sort of thing is what we should be moving towards, and I’ve actually been working on some of these ideas already.

  • http://www.galasoft.ch Laurent Bugnion

    Hey Glenn,

    Great post, and yes, code behind is ok as long as it is view related.

    One thing i want to mention is a 3rd approach to ‘kick’ an action when selected an item: you can add a property of type ICommand to your VM and use that (with paramters if needed). To speed things up and make the code cleaner, i prefer to use a RelayCommand, but of course other implementations work as well. The command is used as a gateway to an action on the VM. In the case of a SelectedItem, it might not be the best solution, but for elements such as buttons etc…, it makes sense to use commands instead of events, and having the command on the VM and relaying the action is a very clean way. It is also possible to test the command in unit tests (though testing the CanExecute can be tricky in WPF because the CommandManager is tied to the UI). Now to be honest, i am not sure if this is what you meant with the solution A, but this would not need element binding (since the command is a property of the VM, which is the implicit data context).

    Of course yet another solution is to use behaviors such as the ones published lately by Pete Blois from the Blend team. This introduces a dependency to the behaviors DLL which can be easily avoided by using something simple like RelayCommand or Prism’s DelegateCommand.

    Looking forward to further discussions about this (and yes now that i am back home i will blog more about all that :)

    Cheers,
    Laurent

  • Clint

    I’ve been wanting to learn WPF and MVVM lately. As someone who is new to these, what article do you think would be best for a beginner?

  • http://codebetter.com/members/gblock/default.aspx Glenn Block

    Thanks Ward!

    Yes i agree with everything you’ve said. Having XAML support a set of conventions I believe (like you) goes a long way. It removes the question of where to put things, rather those concerns just vanish into convention thin-air.

    I hpoe once day our platform supports more of a convention driven approach. We’ve got a great head start with ASP.NETMVC, but hopefully we’ll keep going with Silverlight and WPF. I know that conventions are not for everyone, but for those who embrace them, they make life oh so easier ;-)

  • http://www.neverindoubtnet.blogspot.com/ Ward Bell

    Excellent. Allow me to pile on.

    One thing I’ve noticed is that XAML, as we know it in Silverlight at least, is hard to keep DRY. Consider what a Binding looks like when you arrange for it to support the display of validation errors and exceptions. You start to see a parade of attributes as in

    Mode, ValidateOnExceptions, and NotifyOnValidationError appear not once but in binding after binding.

    This is just one example. Suppose you find a way to rinse this detritus away (and please tell me about it … I sure miss Markup Extensions in SL).

    Even if you beat this one, the tendency creeps back in. We start marking up the code with all kinds of behavioral concerns that are easy to get wrong, hard to debug, and just are not what designers are good at.

    For it is also my experience that Designers are as bad at writing clean code as I am at writing good looking views.

    Finally, I’ll mention that the habit of marking the heck out of every little thing clouds our ability to see programmatic opportunities.

    Maybe we shouldn’t be marking up Person.Name at all. Maybe, if we had an easy way to walk the XAML tree, we could automate the wiring of the binding by letting convention tell us that “Person.Name” is accessible from the ViewModel.

    Now, we write XAML such as

    .

    A one-line wizbang in the code-behind constructs the binding for us … and not just for this TextBox but for every control bound to a property of Person.

    I want smaller XAML, not XAML gone wild … XAML gone wilder still through the generative powers of Blend. I’ll trade a line or two of easy-to-read, easy-to-write, concentrated, testable code-behind in exchange for a big reduction in XAML.

    I know I’m not telling _you_ anything, Glenn … because I know you worked on this very thing

    But readers of this post should realize what we sacrifice when we seek to program with ever-more-clever XAML markup.

    Again, way to go in clearly laying out the positions and teeing up this discussion.