MVC: The Most Vexing Conundrum

Patterns: Patently Perfect!

If you’re still reading this, I’m going to operate on the assumption that you don’t know what MVC is but are, perhaps, cautiously curious. Well, if you’re cautious, buck up! It’s not that difficult to understand once you find a good explanation, and curiosity may have killed the cat but you’re a human and a little sturdier than that, right? And anyway, it’s hard to get killed reading a blog unless you drown in someone else’s self-pity.

Design Patterns: Templates for Programmers

Design patterns are templates so that programmers don’t have to reinvent object-oriented software architecture. Design patterns come about when learned people sit down and figure out the best general way to design a program’s overall functional structure when using object-oriented programming. We’re not talking where you put files, or what your methods do, but how, in an abstract sense, all your programming pieces fit together. Think of them as basic blueprints for your applications—you have your foundation and your steel girders pre-ordained, but the color of the bathroom tile is up to you.

What Every Good Programmer Knows (and Sometimes Does)

If you program much, your code probably migrates towards a higher overall quality over time. In fact, if you’re a smart programmer, the way you design your overarching code structure probably evolves over time as you learn from your mistakes—or rather, from having to go back later and maintain your mistakes (or other peoples’).

So, the hard way, you probably learned that intermixing business logic (the nuts and bolts of your script) with display logic (“if they’re not logged in, show this”) is a Very Bad Idea. And you might have realized that it's a Pretty Good Idea to cordone off sections of your basic web app so that they interoperate, but aren’t inseparable. You’ve probably even learned to write a number of little functions that each do just one simple thing and then have larger aggregator functions that call them in order.

If all of what I’ve said above is true, you’re utilizing a very rough and informal kind of design pattern, and you’re almost two thirds of the way to MVC.

That Most Vexing Conundrum

MVC is one of the most famous and popular design patterns for creating applications with user interfaces, and not particularly vexatious in and of itself. Again, MVC stands for Model/View/Controller, which was apparently assembled as an acronym in no particular order. (MCV or CMV might make more sense, but for some reason neither are as euphonious as MVC.) MVC has three distinctive components, and if you separate them appropriately you end up with a program that is much more portable, scalable, and maintainable than if you hadn’t.

The Bits & Pieces

Sometimes order is important. I'm describing these three components from the ground up. They're all interdependent, certainly, but this is really the natural order of things:

Models are the foundation. Hooray for cinderblocks and cement! A model is commonly something that represents a table of data; in Rails, you have to create a model, one for each table, which describes the relationships (if any) to other models (tables). Without a model, you're unable to actually do anything with any kind of data. Wouldn't that be fun? A web app without data! It'd be almost like a movie without acting...

Controllers are the power tools. Controllers are the tools you use to manipulate data described in the models. When it comes to CRUD operations, manipulating data, and anything that’s considered “business,” controllers are where it’s at—literally. The controller is the one that does all the data validation, the data reading and writing with the help of the lovely model, and hands the finished product off to the view to display. (Full disclosure: in Rails, some data validation is in fact built into the model handling, but this isn't really typical.)

Oh, crud! Don't know CRUD from any other 4-letter c-word? See my previous article.

Views are the spackle and paint. Views let you actually put a face on the application. In the case of web sites, this is the point where your data goes out over the wire, be it in HTML or XML or what-have-you. You're only allowed to have display logic in views—such as looping through content, and hiding or showing links based on who's logged in.

MVC Diagram

But... er... Why?

It’s not a bad question. There are several answers:

  • Separating business logic (controller) and display logic (view) let you easily change the appearance of your application at any time.
  • It makes it easier to make changes behind the scene in the business logic department, too—your code will be oh-so-readable.
  • One word: reusability. You write some cool stuff in Rails (or other MVC outfit). You want to use it again later. You have absolutely no problem, it’s almost as easy as drag and drop, because your code is sweetly compartmentalized.
  • Having models separate from controllers gives ActiveRecord the ability to work its magic—which spares you from having to write queries all over the place.

So... Wasn’t This About Rails?

Right you are! This is about Rails. See the diagram above and follow along.

When you’re working on your Ruby on Rails app, you’re forced to do MVC to a large degree. The Model part of MVC is handled by ActiveRecord; you create a new model in /yoursite/app/models/ using script/generate model and then you open it up and edit it to describe how that model relates with the others.

You have to build a controller, too, and you do that with script/generate controller. Controllers are found in /yoursite/app/controllers/ and generally you have one controller per model, although you can have controllers without models, too—they can control other controllers (gasp!).

And lastly, views, which you will find in /yoursite/app/views (noticing a trend here?). In Rails, you build views in .rhtml template format—an intermixing of HTML and Ruby/Rails code in <% %> tags. No business logic allowed! Ahh, it’s lovely.

Wrappin’ it Up

That’s it for today, folks. But I’ve found some time recently to play around more on the Rails code side of things, and so I’ll be writing about that too soon. Nobody’s popped up in the mean time to write any more really good tutorials so be sure to come back because I plan to be the one to fill that void.

posted in: articles    |     26 comments