Posts Tagged ‘ViewModel’

A History of Violence against HTML

[This is the second in a series on the use of MVC for building web "applications".]

HTML was designed as a document format with hypermedia connections to other, related documents. Today, however, we abuse HTML and treat it as an application platform. It somehow performs remarkably well in most cases. I suppose that’s a testament to the agility of declarative markup. Nevertheless, I think we could all agree that HTML at least started life as a document format. If this is the case, I argue that HTML is not a view format; rather it is a serialization format for a model.

I’m sure many reading this are probably calling me a fool or worse. Well, don’t take my word for it. Let’s look at what some of the leading web developer/designers are saying:

In markup, semantics is concerned with the meaning of an element and how that element describes the content it contains.
-Molly E. Holzschlag (http://www.informit.com/articles/article.asp?p=369225&rl=1)

Although it might be tempting to use the visual layout as the basis for the structure of your markup, this could lead to you overusing elements, particularly <div> elements. This will also result in establishing your content order primarily to accomplish the visual layout rather than it making sense when no style sheets are available. To avoid presentational markup and ordering problems, begin by first looking at the content and then working out from the meaning(emphasis mine).
-Andy Clarke (Transcending CSS)

The notion that HTML is a display language has been proven long ago to be a Bad Thing. CSS taught us to separate our presentation from our content, and the doors that opened when we did it were invaluable. Today, however, we’re still delivering web applications as HTML documents with a bit of scripting layered on top. This works, but is strangled by all of HTML’s limitations. Fundamentally, HTML is not an application delivery format, it is a content description language, despite the valiant efforts of the HTML5 Working Group.
- Meitar Moscovitz (SVG Is The Future Of Application Development)

No, I can’t quote them directly, but I believe my argument has the same spirit. We should look at HTML as a PresentationModel, or ViewModel if you prefer, in the client (i.e. the browser). Therefore, HTML be treated as a serialization of your object model into a document format.

What then is the view? What’s the controller? These are excellent questions. Let’s think about how MVC works. The controller is responsible for receiving requests and relaying responses. The view is supposed to display the representation of the model. For the web, the controller easily aligns with the HTTP protocol and the view to the styles, transforms, and behaviors applied to the model (our HTML document). (I’ve used styles and transforms here separately to emphasize the potential use of XSLT stylesheets in addition to CSS.) Sure, using a document serialization, you could just display the model directly, and the confusion of HTML is here emphasized. It’s a model built out like a visual representation.

Are there some exceptions to this? Sure. If you want to treat HTML as a purely view format, then you can eliminate everything from your HTML except for JavaScript bindable areas and use JSON objects as your PresentationModels. Pass some of those around instead of HTML, and you’re really treating HTML like a true view. However, we don’t generally do that. We usually serialize the model into the HTML and apply our view aspects afterward via CSS and JavaScript.

If we really want to get serious about making an excellent MVC framework, we have to recognize and use our building blocks appropriately. HTML is a model serialization format. Treat it as such.

ViewModel Futures

Glenn Block asked two questions on Twitter tonight that were too good to pass up. First, do you want better tooling, more testable data binding, or a ViewModel base class? I agree with whoever said patterns exist to make up for faults in a language; however, in this case, I think I would choose enhancements to data binding. It’s a little too magical, imho.

I would like to see a ViewModel base eventually, though, as that would be one less thing to wire up myself, and it hopefully silence all the people complaining about the lack of a model in MVC. (Yes, I am thinking the backend models should be sharable among WPF, Silverlight, and MVC.)

Glenn’s second question related to tv target audience. I am always a fan of simple explocicity, to borrow a word from JB. I think that’s what the experts use. Also, I don’t know many who want to me mediocre some day, so going for the best and letting it trickle down is a great idea.

Just my $.02.

Composite WPF Patterns

Microsoft’sComposite Application Guidance for WPF (Composite WPF) gives WPF a lightweight yet effective application block with which to build exciting applications. However, the biggest struggle is deciding on a pattern for applying the library. The Model-View-ViewModel (MVVM), mentioned across the web as the perfect pattern for implementing MVC with WPF, was for some reason not specifically mentioned in the Composite WPF documentation. Nevertheless, the MVVM pattern is many times used and alluded to under the name PresentationModel and is arguably the best approach in most cases.

Dan Crevier posted a series of excellent articles defining the pattern and giving examples of the implementation of MVVM in WPF. These were written several years ago, before development of the Composite WPF block, but they are simple to understand and can give added understanding to the objects included in Composite WPF. For example, his post on encapsulating commands is very similar to the DelegateCommand object provided with CompositeWPF, though the latter uses lambdas to define Execute and CanExecute methods, whereas the former uses a base class and inheritance to define the methods. Using Dan’s example, the equivalent DelegateCommand, contained within the DelegateCommand’s definition, would look something like this:

public DelegateCommand<object> MyCommand { get; private set; }

public Window1()
{
    InitializeComponent();
    MyCommand = new DelegateCommand<object>(
        p => {
                 string text = p as string;
                 // Do something with text
             },
        p => !string.IsNullOrEmpty(p as string));
}

Dan’s definitions of the Model, which he calls DataModel, View and ViewModel match very closely with Composite WPF’s PresentationModel pattern. In this case, the DataModel is a representative object that is fit for display within the View. Using the entities generated for Linq to SQL, you might add properties to the partial classes create the necessary properties to which to bind. These classes should also implement INotifyPropertyChanged so that other DataModels can respond to changes from another, related View and update their data accordingly.

The View should use bindings for everything. The beauty of WPF is truly in its DataBinding functionality. The observer pattern is built right into the Binding, so that whenever one view changes, other views are notified by their bindings to their DataModels. Even the actions to be performed on a user interaction with the UI can be removed to the ViewModel, DataModel, or in the case of Composite WPF, a controller, Shell, or App level, as appropriate. This leaves the View looking very passive, indeed, which greatly helps when unit testing.

The ViewModel is the actual PresentationModel. It hosts the DataModel, as well as the View’s commands. ViewModel should be the object used to bind to the View’s DataContext and should implement INotifyPropertyChanged if any of the properties could change. The QuickStarts and RIStockTrader examples provide excellent samples of the PresentationModel, though be warned that the examples often use different patterns, if for no other reason than to show other pattern implementations.

That covers the MVVM pattern. However, there’s one more aspect that needs to be covered: composite regions. Composite WPF provides regions for managing the display of different modules in the Shell, but what if you need to display multiple modules or views within a “summary” view that is already on the Shell? In this case, you can use a Controller to manage the child use cases. The UIComposition QuickStart shows a terrific example of creating a controller in a ViewModel for the purposes of managing child use cases. This removes the dependencies and depth of a View that includes a tab control containing a large number of child use cases. (The UIComposition QuickStart uses a Supervising Controller pattern instead of the PresentationModel/MVVM pattern, so you’ll have to adjust it accordingly, but it works beautifully.)

The MVVM pattern is a great solution for WPF applications by allowing WPF’s DataBinding and Commanding to remove much of the logic formerly found in the View layer out to a unit testable ViewModel. The architecture stays clean and also fairly shallow in that an additional Presenter class is unnecessary (as opposed to the Supervising Controller pattern.)

Additional Resources:
John Grossman – Tales from the Smart Client
Pete Weissbrod – Model-View-ViewModel Pattern for WPF: Yet Another Approach