I’ve long admired Josh Smith’s work. He’s one of the best explainers on the web and he – together with Karl Shifflett and Andrew Smith - gave us Mole, the superb WPF Visual Studio debugger visualizer.
I heard recently that he’d published an e-book on Model-View-ViewModel (MVVM). I met him for the first time at the Microsoft MVP Summit last week and he graciously handed me a printed copy. I devoured it on the plane home and spent the next day playing with the code and preparing this review.
It’s called “Advanced MVVM” and you can buy a printed copy for $20 or get it for $15 on the Kindle. The companion code is freely available at AdvancedMvvm.com.
$15 bucks for a 52 page “book”? It’s more of an extended essay to be honest … an essay with code. After spending some pleasurable hours with both book and code I thought “where do you get that kind of entertainment / self-reflection for $15?” I have a surfeit of 600 page sleepers lounging on my bookshelf at home; paid more then $50 for each and hardly cracked them. Should we pay by the pound? So I’m over it. I don’t mind paying for the hours Josh poured in and the fun I got out. Set your expectations appropriately and you’ll feel fine.
---- 19 March 2010 Note ---
Ok, it’s been a month or so since I wrote this. Life happens while you’re making plans. I intended to be among the first to comment on it. I’m late to that party (although I have deliberately NOT looked at what others may have said) so I’m not sure if it’s still timely. I also shared it with Josh last week to see if I had missed something and get his feedback, particularly in light of my critical remarks.
He encouraged me to publish it even at this late date. I hope he’ll repost here some of his responses to the points I raised.
----------------------------------
MVVM has spooked a lot of developers. There’s more than a whiff of astronaut architecture about it. There have to be at least 20 MVVM frameworks and no end of contentious arguments to confound and distress you. No wonder so many are put off.
MVVM in a Nutshell
In fact MVVM is fundamentally a simple idea. It starts with the realization that your application is an intractable mess in part because you dumped all of your UI logic into the code-behind … with the help of Microsoft tools. You discover the wisdom of pulling much of that logic out into a companion class (and some helpers) leaving the view class to concentrate on looking pretty and capturing user gestures. The view and its companion must talk; you can structure their conversation according to a variety of familiar patterns. Model-View-ViewModel is one such pattern.
The predominance of automated binding is the hallmark of MVVM. You bind a View’s textbox to a string-providing property of the ViewModel so that a user’s changes in the textbox flow to the property and so that programmatic changes to the ViewModel property flow back to the textbox. You bind View events (e.g., button click) to event handlers in the ViewModel enabling user gestures to be conveyed to the ViewModel.
You could write your own bindings by hand, pushing and pulling data and events with custom code. That’s a lot of work. The XAML-based client technologies (WPF and Silverlight) provide a binding framework that requires little to no custom coding. In most cases you can “connect the dots” declaratively and it just works.
Now the View concentrates on appearance and the ViewModel feeds the view. This separation is both clarifying and liberating. You can start looking at that ViewModel to figure out what it should do and how it should do it without also worrying about the visuals. The subsequent examination of ViewModel’s more limited responsibilities sets you on a more sustainable course. At least this has been my experience … and that of the hundreds (thousands?) of other developers who’ve adopted this pattern.
Now you’ll note that I said it “sets you on course”; I did not say it delivers you to the promised land. There are details to work out. If the View looks to the ViewModel for data, where does the ViewModel get that data? Are we talking about data values alone or the business rules that surround that data, rules about data validity, integrity, security, and persistence?
Many of us draw a circle around these concerns and call that circle “the Model”, the third element in the MVVM triad. Our guiding intuition is this: “the persistent data are definitely in the model and if the rules about data are true for this and every possible UI, the rules belong in the model as well.”
If the last name is required, it is required everywhere; that’s a model rule. If gold customers can select from several thank-you gifts, that sounds like UI logic to me … and belongs in the ViewModel. The specifics have to be worked out.
Back To Josh
At this point the discussion risks slipping into theory and theater. We could run to the white board, scribble madly, and count angels on pins without writing a line of code. I love doing that.
Josh has taken another direction which is likely to be both more popular and more effective. He briefly presents his take on MVVM in clear, accessible prose … and then makes it tangible with an extended exploration of a meaty sample application. I’ve read plenty of pattern papers; I don’t remember any that were so thorough … and entertaining … in their examples.
For style and substance this is a remarkable achievement. I truly hope that Josh’s book is widely read because I think it has a better chance of helping WPF and Silverlight developers feel comfortable about MVVM than anything else I’ve seen.
I’m a little worried that some will fear the word “Advanced” in the title. The term “MVVM” is forbidding enough and many folks are still looking for the introduction. I think this book is the introduction they really need.
In what sense is it “advanced”? It’s far from the last word on the subject. It won’t settle any arguments (least of all mine). But it does rise above the introductory level in two important respects.
First, it considers the implications of multiple, cooperating MVVM instances. Most MVVM articles present a single MVVM-triad: a single View and its companion ViewModel and Model.
No application needs a single MVVM triad. If you have a one-screen application, don’t use MVVM; it’s overkill. MVVM is for multi-screen applications consisting of multiple MVVM triads which spring to life somehow and somehow interoperate.
Second, as I noted earlier, Josh doesn’t just talk about the pattern. Most of the pages describe the accompanying game, BubbleBurst, which is implemented in MVVM style. Instead of paeans to principles and their wondrous benefits, you see MVVM in action, warts and all.
BubbleBurst is “advanced” enough to both introduce MVVM and reveal important implementation challenges of multi-MVVM applications. Yet it’s simple enough to be easily understood in the pages of a book or in a few hours spent trolling the code. It’s also fun to play.
Proceed with Caution
I’m about to begin my critical remarks. Before I do, I want to reemphasize my enthusiasm for what Josh has accomplished. This book is a wonderful place to begin your MVVM journey and I found it to be an enjoyable and insightful read. So, hell-yes, I’m recommending it.
On the other hand, it would be a shame if developers stopped their education here. Important elements of the story are missing and many recommendations are seriously misguided in my view. Readers should take Josh seriously but, once they are comfortable with the pattern, they should become aware of starkly contrasting perspectives as well.
Critical Omissions
Four vital topics are neither covered nor illustrated in the code:
- Testing
- Model (the first ‘M’ in MVVM)
- Dependency Injection
- Event Aggregation
Testing
Josh asks “What is the point of having ViewModels?” First among his reasons: “the ability to easily write unit and integration tests for the functionality of the user interface without having to get into the messy world of writing tests for live UIs.”
That’s the last we hear of testing. There is not a single test in the code base. If testing is as important as he says, I’d expect a thorough treatment starting with building a test regimen and showing, by example, how to write good tests. Instead, we get lip service.
I don’t think testability is the only value of MVVM. I couldn’t recommend it for this reason alone. MVVM is a significant architectural investment that introduces complexity. I wouldn’t incur that complexity cost merely to make my UI testable. I’d look for a less onerous route. Fortunately, I think it has other benefits such as clean separation of concerns, improved readability, and easier debugging (try break-pointing XAML!).
But testability is both a motivation for and a by-product of MVVM style and it should have been covered thoroughly in an “advanced” treatise on MVVM.
Moreover, the design would have benefitted greatly from attempts to test it. Many lines of view code-behind are both untestable and harder to follow than they should be. I see early signs of the spaghetti code that afflicts more complex and mature applications … a drum I’ll beat furiously later in this review.
At almost 300 lines, the BubbleMatrixViewModel begs to be tested both for quality and to reveal the expectations latent in its 20+ public and internal members.
The Missing Model
The pattern is called Model-View-ViewModel. Josh’s Model is nowhere to be found. Model and ViewModel are combined and it’s not clear to me how one would disambiguate them.
The absence of Model isn’t blatantly obvious in a simple game like BubbleBurst. The game doesn’t to retrieve or save objects to a persistent store. We aren’t expecting much in the way of business model logic either; there’s nothing of interest to validate or secure. So the lack of a model is not a deep fault of this particular application. Indeed, it’s a convenient way to concentrate our attention on the central issues for most students of MVVM:
- What code belongs in View and what code in ViewModel?
- How do View and ViewModel interact?
- How do you instantiate Views and ViewModels?
Nonetheless, we can’t pretend to provide a comprehensive guide to MVVP without talking about the Model and how it interacts with ViewModel and (to a lesser extent) View. A business application will demand a clear delineation of responsibilities and equally clear communication paths.
I’m not letting BubbleBurst off the hook either. I felt on several occasions that some ViewModels were heavier and more complicated than they should be because an inchoate game model was not independently defined.
Dependency Injection
I appreciate that Dependency Injection frightens many developers. You can discover MVVM without learning about Dependency Injection. Josh can kind of get away without it as long as he doesn’t test his ViewModels and doesn’t have to think about the services required to manage a persistent model.
But I feel you can’t call this “Advanced MVVM” … or even “Intermediate MVVM” … without introducing DI at some point. In Josh’s application, every View and every ViewModel class is known to and instantiated by some other View or ViewModel class. That won’t fly in real-world applications which have Views and ViewModels that are ignorant of each other.
The constructor of the BubbleMatrixViewModel instantiates three concrete bubble components: BubblesTaskManager, BubbleFactory, and BubbleGroup (twice) before making heavy use of them. That’s a lot of dependencies that would make this ViewModel brittle and especially difficult to test.
Taking hard dependencies means Josh can freely assume that ViewModels will always have parameterless constructors and can always be instantiated in XAML, as he often does here. Someone new to MVVM might think this is the norm. It is not.
Josh himself alludes to DI as one of the avenues opened by the MVVM pattern: “[MVVM] means that you can use frameworks like MEF to dynamically compose your ViewModels, to easily support plug-in architectures …”. That’s the last we hear of MEF or dynamic VM composition.
Again, I think we can ignore DI in an introduction to MVVM; we cannot ignore it in an advanced lesson on MVVM.
Event Aggregation: communicating with the unknown
All of Josh’s MVVM triads are statically determined. Their relationships to each other are fixed and well known.
I was surprised to see a ViewModel for one view hold a reference to a ViewModel of a subordinate view. That’s not how I do it; my general rule is that MVVM triads do not hold references to each other. I concede that the rule makes it difficult to organize cross-triad communication. Josh’s approach is simple and elegant … when available.
In real-world business applications, the MVVM triads often can’t know about each other. They are often defined in separate modules without mutual references. Views appear and disappear dynamically. Direct communication is frequently impossible.
That’s why so many so-called MVVM frameworks include some kind of messaging or Event Aggregation infrastructure. You don’t need them to understand MVVM triads in isolation. But you never see an application with a single MVVM triad and you rarely find an MVVM application with statically determined, session-permanent views. No “advanced” treatment of MVVM can neglect Event Aggregation.
View First or ViewModel First?
Here’s an incendiary topic Josh leaves untouched.
I see two ways to ask this question:
- Do I design the View first or the ViewModel first?
- Do I instantiate the View first or the ViewModel first (or does something else instantiate and wed them)?
The answer to both questions need not be the same. For example, you could decide to design the ViewModel first and let the View instantiate that VM at runtime. This is plausibly the approach advocated in BubbleBurst although Josh never talks about it.
Again, it’s important that readers new to MVVM learn that Josh’s way is not the only way.
View and ViewModel Design
In my experience there is a “dialog” between View and ViewModel design. The VM exists to serve a view even as it strives for independence from any particular concrete view. A VM is useless if there is no view that will work with it; clearly the VM developer must heed the imprecations of the View developer.
On the other hand, in business applications the application’s imperatives – what the view must do to satisfy business requirements – are the province of the programmer and are best articulated through the capabilities of the ViewModel.
Therein lies the necessary tension between View and ViewModel design. As a developer my allegiance is with the ViewModel (“the application should do something worthwhile”) but it would be silly to defend that allegiance at the expense of the View (“a good UX is essential to making an application easy to learn and to use”).
I’d have liked to see this tension at least acknowledged and perhaps explored.
Who begets Whom?
Runtime construction is a question apart from the matter of who drives the design. WPF and Silverlight tooling push you toward “View First” construction in which the View instantiates the ViewModel. You’ll often see the View’s DataContext set by a ViewModel instantiated in the XAML as shown here:
<UserControl.DataContext>
<viewModel:BubbleBurstViewModel />
</UserControl.DataContext>
Contrast this with the ViewModel first, code-based approach (not seen in BubbleBurst) in which the ViewModel is assigned to the View’s DataContext as follows:
view.DataContext = viewModel;
The View First approach assumes that the ViewModel can be created via a default, parameterless constructor. That’s fine for BubbleBurst but wholly unrealistic in business applications whose ViewModels have dependencies (e.g., on the domain model).
Neither WPF nor Silverlight XAML support the dependency injection mechanisms that many of us prefer. I wish Josh had talked about this and perhaps discussed the interesting attempts to use MEF dependency injection (via properties rather than constructor arguments)
I’m not trying to settle these questions. I am saying these questions could have been called out in an “advanced” book on MVVM patterns.
What Belongs In Code-Behind?
Do we allow or prohibit code-behind? That’s a fist-fight topic. Josh looks for a Goldilocks solution, suggesting the amount of code-behind is just right if confined to “logic scoped to the view”.
Such guidance is far too loose in my opinion. It’s not effective guidance at all.
We choose presentation separation patterns in part because we want to minimize testing of the view. We should test any custom logic we write – no matter how it is scoped. The poverty of our testing tools means that, in practice, we will not test the code in the view. Therefore, any code in the code-behind is suspect.
I am open to some code in the code-behind; the “InitializeComponent” method is inescapable. I’ll accept a minimum of “switch board” code in the code behind; direct wiring to a ViewModel member is ok in small doses.
I draw the line at decision logic. I smell a rat when I see a conditional statement of any kind. That’s where bugs breed. Conditional logic is code we should be testing.
I much prefer this rule: “No conditional logic in the code-behind”.
That’s unambiguous. We don’t have to wonder what “scope of the view” means. If there’s an “if” or a “switch” statement, something is wrong. You can detect a violation with automation or visual inspection. It’s a rule that’s easy to follow and pretty easy to abide by … when you know how.
What happens when you don’t follow this rule? You’re lured into the kind of dodgy code that … well we see in the innocent seeming BubbleMatrixView.xaml.cs.
In fact, far from being “best practices”, I’d say that the View code in BubbleBurst represents some of the worst practices.
Look at the HandleMatrixDimensionsAvailable method. This event handler is wired to a UI element in the BubbleBurstView. Unfortunately, the UI element happens to be in a different view, the BubbleMatrixView! One view’s code-behind is wired to members of another view; that’s the road to perdition. That would never pass my review.
I wanted to clean it up immediately. I tried to find the intention behind this practice. Usually I look to the name of a method to discover its purpose. Unfortunately the handler is named for the moment when it is called (“Matrix dimensions available”) rather than for what it does. That’s conventional naming for event handlers but not terribly informative. Unless a handler is brain-dead-simple, I have it delegate immediately to methods with meaningful names. The handler tells me when something happens; the inner method tells me what will be done.
Had Josh adopted my suggestion, he’d have realized that his handler has multiple responsibilities:
- wires the outer window’s keydown event
- picks up the dimensions of the related view’s grid
- starts the game
That’s too much work for code-behind in my book.
When we strive to apply the “no conditional logic in the code-behind” rule, we discover other design problems.
It appears that Undo logic is distributed between two ViewModels. One of them, the BubbleBurstViewModel, determines if undo is possible while the second, BubbleMatrixViewModel performs the undo. Probe further and we find that even the BubbleBurstViewModel test for undo-ability is delegated back to the BubbleMatrixViewModel. The ping-ponging among Views and ViewModels is confusing; it doesn’t smell right.
All the signs suggest the real action is in BubbleMatrixView and its ViewModel.
BubbleMatrixView.xaml is short and sweet.The code-behind in BubbleMatrixView.xaml.cs is another story. Five Region tags sound the alarm. You shouldn’t need region tags in code-behind. Here they barely disguise the complexity of 145 lines of code-behind. That can’t be right.
MicroControllers: BubblesTaskPresenter Example
I was able to refactor the 53 lines dedicated to animating bubble tasks. Most of them went to a BubblesTaskPresenter class, a component Jeremy Miller calls the “MicroController”.
Every MVVM developer should become familiar with the “MicroController” approach.
A “MicroController” performs a narrow UI task on behalf of a view. We usually write one to encapsulate UI logic that is reused across multiple views. That’s not the case here; the application is too small.
We also write MicroControllers to encapsulate UI-specific functionality in a UI-agnostic wrapper. They make it easy for non-UI components, such as ViewModels, to invoke the UI-specific behavior we find in Views. That’s what we need here.
I noticed that the ViewModel holds a TaskManager which raises a PendingTasksAvailable event when there are bubble display tasks. This sets off a sequence of calls between View and ViewModel which collectively “process tasks” queued up by the ViewModel.
Josh’s original code forwarded the event to the View’s code-behind. That code-behind then extracted the VM’s TaskManager and called into it. 53 lines of code-behind are dedicated to this entire process.
After my revision, the view merely provides the ViewModel with a configured MicroController, here called a “BubblesTaskPresenter”:
_bubbleMatrix.BubblesTaskPresenter = new BubblesTaskPresenter(_bubbleCanvas);
This is what switchboard code should look like. I’d like to get rid of the instantiation but at least there is a bare minimum of logic and no conditionals.
The ViewModel receives the concrete presenter in the guise of a UI-agnostic interface, IBubblesTaskPresenter and wires itself to the presenter’s events.
public IBubblesTaskPresenter BubblesTaskPresenter {
get { return _bubblesTaskPresenter;}
set {
_bubblesTaskPresenter = value;
_bubblesTaskPresenter.Completed += delegate { ProcessTasks(); };
TaskManager.PendingTasksAvailable += delegate { ProcessTasks(); };
}
}
private void ProcessTasks() {
var task = TaskManager.GetPendingTask();
BubblesTaskPresenter.PresentTask(task);
}
IBubblesTaskPresenter uses simple .NET types and looks like this:
/// <summary>
/// Interface for a presenter of <see cref="BubblesTask"/>
/// </summary>
public interface IBubblesTaskPresenter {
void PresentTask(BubblesTask task);
event EventHandler Completed;
}
Where did the 53 lines of code-behind go? Into the BubblesTaskPresenter.
What has been gained? Did I just hide the pea under another untestable cup called a “presenter”? Is this merely an academic exercise?
I don’t think so. True, the presenter is dependent upon WPF and upon BubbleCanvas in particular. But it could be tested with a faked canvas and a faked factory. Testing aside, it’s small and focused; it’s easy to see what it does and how it works. It won’t get lost amidst the other motions of the BubbleMatrixView. We might someday use it in another view that presented BubblesTasks.
The BubbleMatrixViewModel has grown a few lines but remains readable and testable; its imported IBubblesTaskPresenter is easy to fake.
The ViewModel no longer exposes the TaskManager. That’s a good thing because the TaskManager is pretty complex piece of machinery with a rich API. We don’t want the View or BubblesTaskPresenter to know about it.
And the View is 53 lines lighter, reducing the anxiety we might justifiably feel if we handed it over to a non-programming designer for styling.
Homework Assignment: if you’re playing along and are looking toward your own application design, you might want to linger over the BubblesTaskPresenter. It is specific to bubbles right now … which is appropriate in the absence of forces that would drive us to generalization.
But you can encapsulate storyboard animations in much this way to both determine state changes within the ViewModel and externalize the animations in “View-space” where they belong. Josh is spot-on when he insists on this separation. The MicroController “presenter” approach is one way to achieve that separation without polluting the code-behind.
Aside: my first presenter was more abstract and general purpose. My generalization was premature. Generalization made the code more complex than it needed to be in this application. I un-factored it to the current version that knows about BubbleCanvas and BubblesTaskStoryboardFactory.
Views Shouldn’t Talk To Views
After clearing out the 53 lines, I was able to focus on what’s left.
I was deeply troubled by the properties of BubbleMatrixView that are exposed to and consumed by the BubbleBurstView code-behind. That can’t be right. Views shouldn’t need custom properties.
If you have to expose a custom view member, you should do so through a view interface. We don’t want any code – View or ViewModel – depending upon a concrete view class. That’s asking for trouble and flies in the face of the testability which justifies MVVM.
It’s also completely unnecessary in this application. As noted earlier the event loop from inner BubbleMatrixView to outer BubbleBurstView leads back around to BubbleMatrixView’s ViewModel. We can cut all that nonsense out and simply update the BubbleMatrixViewModel directly in the code-behind … without any conditional logic.
I refactored as follows:
- Removed 30 lines from BubbleBurstView code-behind
- Added “StartTheGame” to BubbleMatrixViewModel; it combines the functions of setting the dimensions (now private) and starting a new game.
- Removed 61 lines from BubbleMatrixView code-behind which now calls StartTheGame when the canvas is loaded. Region tags are gone.
The BubbleMatrixView code-behind is now a trim 30 lines with no conditionals, down from 145 (80% reduction). Of the 30, exactly 5 of them do work.
My cleanup involved eliminating several null checks. They never did anything useful. First, the variables could not be null in practice. Second, even if they were (e.g., someone broke the xaml), the application would not have functioned anyway. I don’t think a blank screen is superior to an exception. The null checks were about as helpful as empty catch blocks.
Tidy-up BubbleBurstView Code-Behind
BubbleBurstView’s code-behind had one remaining “if” and some other code that I felt didn’t belong there.
Key monitoring logic contained an “if” statement. At first it seemed like key monitoring was a candidate for another MicroController. But there is only one key to handle, the key for Undo. That wasn’t worth the overhead of another MicroController component. Instead I decided to enrich the BubbleBurstViewModel with an Undo method whose signature is:
public bool TryUndo(bool shouldTry) // returns True if undid
The code-behind calculates whether the key presses amount to an undo request. The call is:
e.Handled = _bubbleBurst.TryUndo(isUndoKey);
I don’t like the isUndoKey calculation but I’ll leave it for another day.
My final bug-a-boo is the LoadBubbleViewResources method which instantiates a ResourceDictionary and plugs it into the application-level resources.
I expected this to be loaded by the App.xaml itself but I suspect Josh wants to simulate the notion that independent assemblies have their own resources. While the “Bubble.View” assembly is not independent – the App.xaml has access to it through its host assembly’s references –, I’ll play along.
In any case, the view’s code-behind shouldn’t know the details of ResourceDictionary construction and App.Resources update. Time for a MicroController: “BubbleViewResourceLoader” which we can invoke from within the code-behind’s constructor for now. It still stinks but it stinks less.
The code-behind now stands at 41 lines, down from the original 86; only 9 of them do work.
Picky, Picky
I’m a restless complainer. I’ve got a few more bones to pick having nothing to do with MVVM.
Page numbers! You may have noticed that my citations lacked page numbers. That’s because there aren’t any in the printed document I’m reading.
The abundance of Region tags annoys me. Hey, I use them too, especially in pedagogical code where I want to unveil new ideas didactically in the course of a presentation.
I appreciate that they seem to organize the code into nice buckets: “constructors”, “methods”, “fields”. But lately I’ve come to believe that they’re more of a code smell.
If the class is short – as it should be – they interfere with my ability to read and grasp the class at a glance. If the class is long, they suggest that my class implements too many distinct concerns and I’m struggling – vainly – to keep them organized. These concerns would be better delegated to supporting classes. I suspect that automated testing would make this defect more obvious.
I’m not thrilled with the data triggers. Data triggers are not available to Silverlight programmers probably for good reason. The Visual State Manager is the preferred choice for both WPF and Silverlight.
A particularly egregious data trigger can be found in BubbleBurstView.xaml where the GameOverView is collapsed when the BubbleBurstViewModel’s GameOverViewModel is null. Could there be a more obscure way to signal that a modal dialog should be hidden? I suspect a bound IsGameOver property would be both simpler and more obvious.
Where’s The Code?
Josh’s original source is at AdvancedMvvm.com . I’ve temporarily posted my refactored version on my site. I’m not promising it will stay there- this is Josh’s code and I’ll do whatever he wants me to do with it (including burn it) – but it’s there now and I’ll let you know if I move it.
Wrap Up
I have high hopes for the conversation Josh has started with this book.
I see it as one place to begin your study of MVVM rather than as the definitive work on the subject. Some of the practices I find dubious and there are serious omissions.
But I gave it this much attention because it deserves it. It’s a fine piece of writing, a carefully considered example, and a push in the right direction. Josh speaks to a broad audience with an authentic voice they understand and respect. He has my respect as well.
It’s well worth the $15 bucks on the Kindle.
Enjoy!
p.s.: Cross-posted to my other
blog on CodeBetter.