Home > Articles > Web Development > ASP.NET

Designing Silverlight Business Applications: the Model-View-ViewModel (MVVM)

In this chapter, you learn about design patterns and why they are important. Jeremy Likness shares 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.
This chapter is from the book

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

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

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020