Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.

Channels ▼

Design Patterns for Web Programming

Design Patterns for Web Programming

Do you need MVC?

June 2002

Between consulting and training, I get to glimpse the inner workings of many different companies and their development projects. Recently, I've noticed that as the demands placed on Web applications increase, some applications aren't up to what's now required of them.

The problem is their simple architectures. Although unsophisticated designs are sufficient for basic, single-purpose Web sites, these same programs often fail when they're extended into new territories. For example, a simple set of Web pages and CGI scripts isn't always a good fit for, say, internationalization. Bundling data into a form that's suitable for VoiceXML or display on a mobile phone isn't trivial either.

Traditional development teams wrestled with similar issues when they made the transition from text-based applications to graphical programs under Windows, the Mac OS, and the X Window System for Unix. The solution that many developers turned to was the Model View Controller (MVC) design pattern.

Many programmers will be familiar with MVC from popular C++ application frameworks like the Microsoft Foundation Classes. I first encountered MVC when I was learning SmallTalk, and I had a lot of trouble with it initially. However, over time I've decided that it really does make sense for interactive applications.

All the same, MVC hasn't yet been widely adopted in Web development. MVC tools for the Web exist; a few frameworks are available, including Maverick (mav.sourceforge.net) and Struts (jakarta.apache.org/struts). But like most design patterns, you don't really need a special tool to use MVC (although, a pre-built tool would probably be easier to use than rolling your own solution). So why hasn't MVC overtaken the Internet the way it has classical application development?

Some developers I talk to don't have a clear idea of what MVC really is. Others think MVC is too much trouble for a Web application. Of course, for a simple page, practically any scripting is overkill. But if you have anything that resembles an application—that is, you interact with the user, accepting input and generating results—MVC deserves your consideration.

What Is MVC?

In a traditional application, a single piece of code handles everything. With MVC, you break down your program into three cooperating parts: the Model, the View, and the Controller. The View is the part the user sees. It formats data into an onscreen representation. However, it doesn't actually contain the data. The data resides in the Model. Finally, the Controller portion accepts user commands and modifies the Model.

Naturally, the Model has to inform the View that it should update the representation of the data when that data changes.

The classic example of this strategy is a spreadsheet program that runs on a personal computer. Using MVC architecture, the Model stores the formulae and other data. When you issue a command to save to a file (or load from a file), the Model handles this action. It also handles the specific logic, like recalculating the entire sheet. The View draws the familiar grid that shows a part of the data (depending on the scroll bar's position). The Controller deals with any process in which the user changes something.

This approach has several advantages. The most obvious is that this decoupling allows for easier unit testing. It also isolates changes to a large degree. Changing the way data is displayed is not likely to affect the document object functions. However, an even greater benefit is the ability to mix and match different parts. For example, you might want to add a pie chart View of the data. Not only is this relatively easy, but you can reuse the pie chart View with other applications that use the same style of document object.

MVC and the Web

In the JSP and Java world, MVC development is often referred to as Model 2. Java developers sometimes use MVC by creating a servlet to act as the Controller. All requests go to the Controller servlet, which then decides which JSP to invoke to process and display the results. The JSP acts as the View, and link or submit buttons within the JSP play the role of Controller. If you aren't comfortable with writing servlets directly, I've seen people write Controllers using straight JSP. (After all, a JSP compiles into a servlet).

Java isn't the only way for Web developers to take advantage of MVC. ASP.Net has some MVC-specific features built into it, as does Apple's WebObjects, but you can use MVC with practically any scripting or programming language. You could even use Perl. For example, the Perl scripts at eXtropia (www.extropia.com) use a custom MVC framework. In fact, you can adapt MVC to any of the popular scripting languages. You simply have to partition your code so that one part handles the underlying data, a second part handles the presentation, and a third part handles the changes and control.

You might also consider using XML to implement your Model. Because the Model part of MVC is supposed to hold the data, it makes sense that modern MVC architectures would work well with XML. Decoupling the View and Controller logic lets the document code focus on the XML parsing. The Views can just assume that they have the data they need without dealing with the intricacies of XML.

Changes in the XML structure only affect the Model code. Of course, with the move to supply XML-based Web services, your document might even be distributed between multiple servers with little difficulty.

XML is a great choice for many applications. Of course, one of the nice things about MVC is that with proper design you could use XML, a database, or even an ordinary file for the data source. If the interface to the rest of the program remains immutable, no one will care where the data originates (except, of course, for the person responsible for the Model).

An ASP Example

Naturally, if your language of choice includes support for MVC, you can expect your program design to be more elegant than if you had to roll your own support. However, MVC doesn't require any particular support from your scripting language. It's more of a philosophy than a specific technique.

To illustrate, I've designed a simple MVC framework using XML that's written in classic ASP. The source code for this framework is available in a downloable zip file. Naturally, there are many ways you might use ASP to implement an MVC strategy, but this simple example is easy to follow and will give you a concrete example of MVC in action.

Even though ASP isn't designed with MVC in mind, the Server.Execute and Server.Transfer methods make it simple for one script to call or jump to another. A request to the controller might look like this:

www.some-web-site.com/control.asp? cmd=viewtable&doc=intlist.asp

The control.asp file serves as Controller, and as an entry point to the entire application. By providing different commands and documents, this simple script reads the document data and passes control to the appropriate View. In addition, the Controller provides defaults for the parameters (cmd and doc) if you don't provide any values.

ASP isn't well-suited for passing data between separate modules, so the document object reads the XML data (using the Microsoft XML parser) and stores the resulting information in the current Session object. As a side benefit, this action also caches the data, so the document object only reparses the XML when necessary. If you have a lot of data, you might have to flip everything around and have the Controller call the View. The View could then call the document and request a particular subset of data. That isn't a problem. MVC requires that each part of the system be responsible for managing its own domain (the data, the control, or the display), but that doesn't mean that the responsible piece can't delegate to another module.

The View, of course, simply formats the data it finds in the Session object. It doesn't know, or care, where the data was before. I'm not seriously suggesting that you'd use this simple-minded example as a skeleton for serious applications. I merely want to illustrate that you can implement MVC in a mere handful of ASP lines. Thus, you should be able to adopt it for practically any project.

Because It's There?

As Web applications become more complex, the advantages of more complicated development techniques like MVC become increasingly evident. The benefits are numerous:

  • MVC simplifies the creation of multiple user interfaces with the same data.
  • It increases the opportunity for code reuse.
  • It lets developers write and debug modules independently.
  • It decouples code, allowing for easier modifications and division of labor between client and server.

The bottom line is that MVC applications are more flexible and more able to withstand change than most ad hoc solutions. Of course, simply because you can do something doesn't mean that you should. But for any application beyond a simple page, you often receive compelling benefits using MVC.

MVC software may take a little extra development effort initially, but that quickly pays for itself in decreased debugging time and increased flexibility. As a bonus, MVC increases the possibility of code reuse, which can further reduce total costs over the life of several projects.

As I've demonstrated, MVC is a methodology you can apply with nearly any development tool. Of course, if you have the luxury of choosing new development tools, you might want to consider selecting one that provides direct support for MVC and makes your life even easier. But in the end, regardless of what you use, MVC can help you design architectures that will withstand the test of time.

Al is the author of many popular programming books including Java 2 Network Protocols Black Book (Coriolis). You can find him on the Web at www.al-williams.com.

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.