Designing Silverlight Business Applications: the Model-View-ViewModel (MVVM)
MODEL-VIEW-VIEWMODEL IS AN ELEGANT WAY TO SIMPLIFY Silverlight development, making it fast and easy; unfortunately, many developers mistakenly believe it is an incredibly complex pattern. A discrepancy exists because developers can’t seem to agree on what MVVM is, often confusing frameworks that utilize MVVM with the pattern itself. Add to the mix over-engineered and overly complex applications, and you have the ingredients for a controversial soup of opinions about MVVM.
In my experience, the proper use of MVVM makes it easier to build applications, especially when you have larger teams or separate teams of designers and developers. The ability to incorporate unit tests also helps reduce the rate of customer-initiated incidents because bugs are caught earlier in the process. Unit tests make it easier to extend and refactor applications, and the MVVM pattern itself allows for what I call refactoring isolation, or the ability to make modifications to areas of the application without having to visit and update every module as a side effect of the change.
In this chapter, you learn about design patterns and why they are important. I share with you a brief history of patterns, what their authors intended, and how this led to the creation of the MVVM pattern. Sections cover each element of the MVVM triad, followed by some of the key features and benefits that MVVM provides. MVVM itself is not a framework, although there are many frameworks that provide implementations of the pattern; MVVM is a UI design pattern.
UI Design Patterns
In medieval times, guilds were groups of individuals with common goals. There were different types of guilds, including the craft guilds, whose members were artisans of specific occupations such as baking and stone-cutting. Guilds might have to provide a stamp of approval for items before they were sold to the common market in order to maintain the quality and integrity of the product. More importantly, guilds would identify the master craftsmen or experts who would then take on apprentices. An apprentice wouldn’t have to figure out everything on his own; instead his master would share the “tricks of the trade” and provide the best practices to get the job done.
In the guild of software development, the master craftsmen use design patterns as their tools of choice. These are simply repeatable solutions for recurring problems that have evolved over time. Sometimes the solutions were discovered by specific individuals, but more often than not, patterns were established independently to solve similar problems and emerged as a common solution when groups of developers shared their ideas. Although every software application is unique, it is often composed of distinct sets of challenges that have already been solved.
There’s a good chance you’ve worked with established patterns even if you didn’t call them by name. Have you created a method that uses an existing object as the template to create a new object? That’s called the prototype pattern. Have you written a data-access layer that uses a generic interface with load, save, and delete methods and then maps those actions to more specific APIs exposed by ADO.NET, LINQ-to-SQL, or some other data provider? That’s called an adapter. Have you ever used a foreach loop in C#? That’s an iterator.
As you can see, there are many existing patterns to solve common problems. Learning patterns isn’t an exercise in hypothetical programming and doesn’t automatically make you a software architect, but it does provide a vocabulary you can use to construct software applications. Just like learning more words helps us communicate better, learning patterns will make it easier to solve existing problems by tapping into proven solutions that have already been tested in the field. This is extremely important in LOB applications when the development teams are larger and members come and go. Ramping up should involve focusing on the business domain more than the general software itself.
Some user interface (UI) design patterns have evolved to solve the problem of maintaining the presentation layer of your application independently of the underlying business logic, services, and data. Some of the problems being solved include the following:
- Fluidity of the user interface—Often there can be significant changes to look, feel, and interaction over time. A well-defined and properly implemented UI design pattern can help insulate those changes to minimize impact on the core business logic and data concerns.
- Parallel development and design—Often the design team is separate from the development team, with different skillsets and involving multiple designers. UI design patterns can maximize the efficiency of this workflow by providing the separation necessary to allow the developers and designers to work in parallel with minimal conflicts.
- Decoupling of presentation logic—There are common patterns in the presentation layer, such as providing a list of items and allowing the user to select a single item, that can be solved in multiple ways (combo box, grid, list box, and so on). UI design patterns help decouple data elements from the presentation implementation so the core functionality can remain the same regardless of how the pattern is presented.
- View-logic testing—Complex view logic is often the domain of developers. Testing the logic is made easier by not requiring a full-blown UI. An example is dependent or cascading lists: Selecting an item in the first list determines the content of the second list. Ideally, you should be able to implement this behavior and test it without having to draw a corresponding combo box control and process click events.
The problem of effectively developing, testing, and integrating the presentation layer has been around since the earliest days of computer programming. The first UI design patterns can be traced back to the late 1970s when a scientist named Trygve Reenskaug visited Xerox’s Palo Alto Research Center (PARC) and wrote a series of reports in an effort to “simplify the problem of users controlling a large and complex data set.” (http://heim.ifi.uio.no/~trygver/2007/MVC_Originals.pdf).
The solution he described eventually came to be referred to as Model-View-Controller, or MVC for short. The same pattern is popular and used today for web-based applications (Microsoft even named their latest framework for web development after the pattern). It defined a separation of concerns between the visual element on the display, the logic to interact with that element, and the rest of the application that represents its perception of the real world through a domain model.
The initial title of the first paper was actually “thing-model-view-editor,” because out of the model comes a thing that needs to be viewed and edited. The essence of the pattern was a separation that looked something like Figure 7.1.
Figure 7.1. The Model-View-Controller (MVC) pattern
The model represents everything in the system that doesn’t involve user input or presenting any type of view to the user. The controller works with the model and coordinates views as well as processes input from the user. The idea is that the view doesn’t ever interact directly with input, but simply receives commands from the controller. The view can also observe the model and present information from the model.
The key to the pattern lies in his description of the controller: “a view should never know about user input, such as mouse operations and keystrokes. It should always be possible to write a method in a controller that sends messages to views which exactly reproduce any sequence of user commands” (http://heim.ifi.uio.no/~trygver/2007/MVC_Originals.pdf).
To summarize, a few simple rules drive the MVC pattern:
- The model is completely ignorant of the UI (view/controller).
- The controller handles the user input.
- The view handles the output by inspecting the model.
- Together, the view and controller provide a reusable control with encapsulated behavior, as shown in Figure 7.1.
Although the MVC pattern achieved a certain level of separation, it does have some limitations. In the original pattern, the view would display values based on observations of the model. The model might represent data in the form of integers. The view, however, might display a bubble chart with various diameters based on the value. In that case, something has to be responsible for taking an integer value and determining what diameter it maps to. The model really shouldn’t be concerned with that task because it is supposed to be ignorant of the UI and the concept of a circle with a specific diameter.
The solution is to introduce a special type of model referred to as the presentation model. This is part of the application tasked specifically with translating information of the model and formatting it into the correct values for the view. It is the presentation model that can take an integer and map it to a diameter. It is still independent of the view in the sense that it does not know how to draw a circle, but it forms a sort of buffer between the pure model and the pure view to provide what is referred to as view logic or presentation logic.
The pattern that uses the presentation model is called the Model-View-Presenter (MVP) pattern. The term was popularized in a paper published in 1996 by Mike Potel (http://www.wildcrest.com/Potel/Portfolio/mvp.pdf). In this pattern, the dependencies and flow were more formal, as visualized in Figure 7.2.
Figure 7.2. The Model-View-Presenter (MVP) pattern
The MVP pattern introduced a few significant changes. First, the inputs (referred to as interactions) are handled by the view. The view observes the model directly to display information, but when the user provides inputs, those inputs are raised as events to the presenter. The presenter then processes those events and sends them as commands to the model.
Although there are several variations of both the MVC and MVP patterns, they are widely recognized patterns that have been used for decades to separate presentation logic from the internal business logic and data that drives applications. It is these patterns that also laid the foundation for the pattern you will learn about in this chapter, the Model-View-ViewModel pattern. This pattern was created and popularized for Windows Presentation Foundation (WPF) but was quickly carried over to Silverlight.