MVC Done Right?

Model-View-Controller (MVC) is a design style that dates back (as so much does) to the pioneering work of the Xerox PARC facility. The idea is that applications should be separated into:

  • Model: the data that the application manipulates, and the fundamental operations it performs on that data
  • View: How the application looks to the user.
  • Controller: How user, view, and model interact.

(Yes, yes, I’m sure anyone who cares to can pick apart my definitions. Don’t care.)

The idea is, views change all the time (today it’s radio buttons, tomorrow it’s drop-downs), controllers change moderately (add a confirmation step, tighten up the authentication), and models hardly change at all (an accounting program isn’t going to change into an MMORPG). So isolate the fast-changing bits from the slow-changing ones. And also allow different specialties — database hackers, usability analysts, graphical designers — to put apply themselves to their own field exclusively.

How do you do that in web applications? The received wisdom of the day is:

  • Model: database + ORM (e.g., Hibernate, ActiveRecord)
  • View: templating language
  • Controller: application framework (Struts, Spring, Rails, etc.)

In other words, do it all on the server, all in one language (which, of course, fits all purposes, because it is the One True Language). Maintain separation of concerns with iron discipline and wishful thinking.

My own view:

  • Model: database + RESTful web service, delivering information in JSON
  • View: Static (X)HTML/CSS
  • Controller: Javascript/AJAX

The model code can be implemented in any server-side language: Java, C#, Ruby, Python, Erlang, whatever; it just needs to be able to talk to the database and send JSON over the wire. The view can be created in an HTML/CSS environment like Dreamweaver, with no worries about whether it’s compatible with the developer toolset. And the controller logic… Well, I’ve been playing with jQuery lately, and it may shock some folks to learn that coding client-side Javascript with a good compatibility layer library is actually fun.

Dividing tasks by physical location and implementation language creates a strict separation of concerns. Server-side code does not generate HTML. Controller code does not do SQL queries. View markup contains no executable code at all: there is no template language. There is zero possibility of the parts bleeding together.

Why wouldn’t this work? Am I missing something?

Comments are closed.