222

As a serious programmer, how do you answer the question What is MVC?

In my mind, MVC is sort of a nebulous topic — and because of that, if your audience is a learner, then you're free to describe it in general terms that are unlikely to be controversial.

However, if you are speaking to a knowledgeable audience, especially an interviewer, I have a hard time thinking of a direction to take that doesn't risk a reaction of "well that's not right!...". We all have different real-world experience, and I haven't truly met the same MVC implementation pattern twice.

Specifically, there seem to be disagreements regarding strictness, component definition, separation of parts (what piece fits where), etc.

So, how should I explain MVC in a way that is correct, concise, and uncontroversial?

2

10 Answers 10

165

MVC is a software architecture - the structure of the system - that separates domain/application/business (whatever you prefer) logic from the rest of the user interface. It does this by separating the application into three parts: the model, the view, and the controller.

The model manages fundamental behaviors and data of the application. It can respond to requests for information, respond to instructions to change the state of its information, and even to notify observers in event-driven systems when information changes. This could be a database, or any number of data structures or storage systems. In short, it is the data and data-management of the application.

The view effectively provides the user interface element of the application. It'll render data from the model into a form that is suitable for the user interface.

The controller receives user input and makes calls to model objects and the view to perform appropriate actions.

All in all, these three components work together to create the three basic components of MVC.

11
  • 7
    +1 I really prefer to think of MVC as an architecture of three (or more) patterns, than a design pattern. There's no canonical implementation, it simply isn't that small, and all implementations will have quite a few more than the implied core components.
    – yannis
    Dec 30, 2011 at 8:43
  • 57
    Though this answer has 21 upvotes, I find the sentence "This could be a database, or any number of data structures or storage systems. (tl;dr : it's the data and data-management of the application)" horrible. The model is the pure business/domain logic. And this can and should be so much more than data management of an application. I also differentiate between domain logic and application logic. A controller should not ever contain business/domain logic or talk to a database directly.
    – Falcon
    Dec 31, 2011 at 13:58
  • 13
    I cannot disagree more with this answer simply because it claims mvc to be rational outside the presentation layer. The rest of the answer is ok. MVC should start and end at your presentation layer and absolutely should not have your business logic and repository in it. Doing so effectively places your entire application in your presentation layer and makes no available API which would allow direct access to your business logic or pure data without it being designed for the originating app. This is not open for extensibility, view models get you closer but you're still missing loose coupling Oct 21, 2012 at 18:46
  • 6
    @Jimmy: In many constructions of MVC, the models can be reused in APIs because they do not have dependencies on the UI -- the separation between view and model takes care of that. But that depends, of course, on how you choose to define 'model'. If you are going to make a judgment about MVC, you should first explain which interpretation of MVC you are using.
    – Owen S.
    Jan 5, 2013 at 22:13
  • 6
    @Yannis: This just begs the question: What is an architecture of patterns? Why wouldn't you call that just another design pattern? The very definition of design pattern in GoF (and Alexander) makes it quite clear that patterns ought not prescribe one canonical implementation (though the popularity of both books undercuts that notion a bit).
    – Owen S.
    Jan 5, 2013 at 22:19
147

Analogy

I explained MVC to my Dad like this:

MVC (Model, View, Controller) is a pattern for organising code in an application to improve maintainability.

Imagine a photographer with his camera in a studio. A customer asks him to take a photo of a box.

The box is the model, the photographer is the controller and the camera is the view.

Because the box does not know about the camera or the photographer, it is completely independent. This separation allows the photographer to walk around the box and point the camera at any angle to get the shot/view that he wants.

Non-MVC architectures tend to be tightly integrated together. If the box, the controller and the camera were one-and-the-same-object then, we would have to pull apart and then re-build both the box and the camera each time we wanted to get a new view. Also, taking the photo would always be like trying to take a selfie - and that's not always very easy.


Detailed Explanation

It was only after reading the following maillist question/answer that I felt like I understood MVC. Quote: https://mail.python.org/pipermail/python-list/2006-January/394968.html

bwaha wrote:

The author refers to mvctree.py in wxPython as an example of MVC design. However I'm still too green so I find that particular example too complex and I'm not understanding the separation the author is recommending.

MVC is all about separation of concerns.

The Model is responsible for managing the program's data (both private and client data). The View/Controller is responsible for providing the outside world with the means to interact with the program's client data.

The Model provides an internal interface (API) to enable other parts of the program to interact with it. The View/Controller provides an external interface (GUI/CLI/web form/high-level IPC/etc.) to enable everything outwith the program to communicate with it.

The Model is responsible for maintaining the integrity of the program's data, because if that gets corrupted then it's game over for everyone. The View/Controller is responsible for maintaining the integrity of the UI, making sure all text views are displaying up-to-date values, disabling menu items that don't apply to the current focus, etc.

The Model contains no View/Controller code; no GUI widget classes, no code for laying out dialog boxes or receiving user input. The View/Controller contains no Model code; no code for validating URLs or performing SQL queries, and no original state either: any data held by widgets is for display purposes only, and merely a reflection of the true data stored in the Model.

Now, here's the test of a true MVC design: the program should in essence be fully functional even without a View/Controller attached. OK, the outside world will have trouble interacting with it in that form, but as long as one knows the appropriate Model API incantations, the program will hold and manipulate data as normal.

Why is this possible? Well, the simple answer is that it's all thanks to the low coupling between the Model and View/Controller layers. However, this isn't the full story. What's key to the whole MVC pattern is the direction in which those connection goes: ALL instructions flow from the View/Controller to the Model. The Model NEVER tells the View/Controller what to do.

Why? Because in MVC, while the View/Controller is permitted to know a little about the Model (specifically, the Model's API), but the Model is not allowed to know anything whatsoever about the View/Controller.

Why? Because MVC is about creating a clear separation of concerns.

Why? To help prevent program complexity spiralling out of control and burying you, the developer, under it. The bigger the program, the greater the number of components in that program. And the more connections exist between those components, the harder it is for developers to maintain/extend/replace individual components, or even just follow how the whole system works. Ask yourself this: when looking at a diagram of the program's structure, would you rather see a tree or a cat's cradle? The MVC pattern avoids the latter by disallowing circular connections: B can connect to A, but A cannot connect to B. In this case, A is the Model and B is the View/Controller.

BTW, if you're sharp, you'll notice a problem with the 'one-way' restriction just described: how can the Model inform the View/Controller of changes in the Model's user data when the Model isn't even allowed to know that the View/Controller, never mind send messages to it? But don't worry: there is a solution to this, and it's rather neat even if it does seem a bit roundabout at first. We'll get back to that in a moment.

In practical terms, then, a View/Controller object may, via the Model's API, 1. tell the Model to do things (execute commands), and 2. tell the Model to give it things (return data). The View/Controller layer pushes instructions to the Model layer and pulls information from the Model layer.

And that's where your first MyCoolListControl example goes wrong, because the API for that class requires that information be pushed into it, so you're back to having a two-way coupling between layers, violating the MVC rules and dumping you right back into the cat's cradle architecture that you were [presumably] trying to avoid in the first place.

Instead, the MyCoolListControl class should go with the flow, pulling the data it needs from the layer below, when it needs it. In the case of a list widget, that generally means asking how many values there are and then asking for each of those items in turn, because that's about the simplest and loosest way to do it and therefore keeps what coupling there is to a minimum. And if the widget wants, say, to present those values to the user in nice alphabetical order then that's its perogative; and its responsibility, of course.

Now, one last conundrum, as I hinted at earlier: how do you keep the UI's display synchronised with the Model's state in an MVC-based system?

Here's the problem: many View objects are stateful, e.g. a checkbox may be ticked or unticked, a text field may contain some editable text. However, MVC dictates that all user data be stored in the Model layer, so any data held by other layers for display purposes (the checkbox's state, the text field's current text) must therefore be a subsidiary copy of that primary Model data. But if the Model's state changes, the View's copy of that state will no longer be accurate and needs to be refreshed.

But how? The MVC pattern prevents the Model pushing a fresh copy of that information into the View layer. Heck, it doesn't even allow the Model to send the View a message to say its state has changed.

Well, almost. Okay, the Model layer isn't allowed to talk directly to other layers, since to do so would require it knows something about those layers, and MVC rules prevent that. However, if a tree falls in a forest and nobody's around to hear it, does it make a sound?

The answer, you see, is to set up a notifications system, providing the Model layer with a place it can announce to no-one in particular that it has just done something interesting. Other layers can then post listeners with that notification system to listen for those announcements that they're actually interested in. The Model layer doesn't need to know anything about who's listening (or even if anyone is listening at all!); it just posts an announcement and then forgets about it. And if anyone hears that announcement and feels like doing something afterwards - like asking the Model for some new data so it can update its on-screen display - then great. The Model just lists what notifications it sends as part of its API definition; and what anyone else does with that knowledge is up to them.

MVC is preserved, and everyone is happy. Your application framework may well provide a built-in notifications system, or you can write your own if not (see the 'observer pattern').

...

Anyway, hope that helps. Once you understand the motivations behind MVC, the reasons why things are done the way they are starts to make sense, even when - at first glance - they seem more complex than necessary.

Cheers,

has

2
94

MVC is mostly a buzzword.

It used to be considered a pattern, but its original 1979 definition has been dumbed down, passed on, misinterpreted, and taken out of the original context. It's been ill-redefined to the point it starts resembling a religion, and while this certainly helps its cargo cultists defending it, its name doesn't associate anymore with a solid set of guidelines. As such, it cannot really be considered a pattern anymore.

MVC was never meant to describe web applications. Nor modern operating systems, nor languages (some of whom actually made the 1979 definition redundant).

It was made to. And it didn't work out.

We now deal with an obscene web-mvc hybrid that, with its awful buzzword status, ill definition, and having semi-illiterate-programmers as a target demographic, makes a really bad publicity to software patterns in general.

MVC, thus, became separation of concerns distilled for people who don't really want to think too much about it.

  • The data model is handled one way,
  • the view in another,
  • the rest is just named "controller" and left to the reader's discretion.

Web sites / web applications in the 1990s did not really use to apply separation of concerns.

They were horrible botches of intermixed spaghetti code. UI changes, redesigns, and data rearrangements were incredibly hard, expensive, long, depressing, and ill-fated.

Web technologies like ASP, JSP and PHP made it too easy to intermix view concerns with data and application concerns. Newcomers to the field usually emit inextricable code mudballs like in those old times.

Thus, a growing number of people started repeating "use MVC" in endless loops on support forums. The number of people expanded to the point of including managers and marketers, (to some the term was already familiar, from those times in GUI programming, in which the pattern made sense) and that became the behemoth of a buzzword we have to face now.

As it stands, it's common sense, not a methodology. It's a starting point, not a solution. It's like telling people to breathe air, or make crunches, not a cure for cancer.

24
  • 23
    It's certainly not mostly a buzzword. It's true that MVC tends to be more pervasive and less distinct than other design patterns, so you might think of it as an organizing principle or paradigm instead. But whatever you call it, it's a fundamental concept in a number of very successful object oriented frameworks. To pretend that it's just a buzzword, i.e. a fashionable phrase that doesn't mean much, is to do a disservice to the OP.
    – Caleb
    Dec 30, 2011 at 6:28
  • 24
    It's a fancy word for pre-existing concepts that didn't really need one. And what design pattern / architecture doesn't fit that description?
    – yannis
    Dec 30, 2011 at 12:30
  • 15
    The data model is handled one way, the view in another, the rest is just named "controller" +1
    – c69
    May 2, 2012 at 19:02
  • 36
    -1. I wish I could -10 for all of the idiotic +1 comments. How is any of this "obvious" given the basic principles of coupling and cohesion? UI architectures abound, including MVC, MVP, MVVM, Forms, and Smalltalk's model. Some companies also push the Composite Application architecture to the extreme, such as in WS-CAF. To say that "common sense" automatically leads you to MVC holds about as much water as Descartes' so-called proof of God. It's obviously what you know, but your answer demonstrates either an ignorance of other methods or an inability to expand your own horizons.
    – Aaronaught
    Oct 21, 2012 at 16:35
  • 9
    @Aaronaught MVP, MVVM, and Forms are reactions to MVC; they're trying to address its shortcomings and to turn its ill definition to something sane and straight forward. They unfortunately turn this "easy peasy, but too blurry to be of any use" MVC model into a "cumbersome all-around solution to problems you'll probably never have" and they need heckloads of boilerplating to be put to good (or some) use. I deeply respect the attempt, though. I only hope future generations will forgive us for having tried to channel commonsense into ready-made-recipes they will have to legacy-maintain.
    – ZJR
    Oct 22, 2012 at 1:08
41

The best way to define it is to go to the original writings of Trygve Reenskaug, who invented it: http://heim.ifi.uio.no/~trygver/themes/mvc/mvc-index.html

This paper, in particular, is generally considered the definitional text: http://heim.ifi.uio.no/~trygver/1979/mvc-2/1979-12-MVC.pdf

MODELS

Models represent knowledge. A model could be a single object (rather uninteresting), or it could be some structure of objects...

There should be a one-to-one correspondence between the model and its parts on the one hand, and the represented world as perceived by the owner of the model on the other hand. The nodes of a model should therefore represent an identifiable part of the problem.

The nodes of a model should all be on the same problem level, it is confusing and considered bad form to mix problem-oriented nodes (e.g. calendar appointments) with implementation details (e.g. paragraphs).

VIEWS

A view is a (visual) representation of its model. It would ordinarily highlight certain attributes of the model and suppress others. It is thus acting as a presentation filter.

A view is attached to its model (or model part) and gets the data necessary for the presentation from the model by asking questions. It may also update the model by sending appropriate messages. All these questions and messages have to be in the terminology of the model, the view will therefore have to know the semantics of the attributes of the model it represents. (It may, for example, ask for the model's identifier and expect an instance of Text, it may not assume that the model is of class Text.)

CONTROLLERS

A controller is the link between a user and the system. It provides the user with input by arranging for relevant views to present themselves in appropriate places on the screen. It provides means for user output by presenting the user with menus or other means of giving commands and data. The controller receives such user output, translates it into the appropriate messages and pass these messages on .to one or more of the views.

A controller should never supplement the views, it should for example never connect the views of nodes by drawing arrows between them.

Conversely, 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.

EDITORS

A controller is connected to all its views, they are called the parts of the controller. Some views provide a special controller, an editor, that permits the user to modify the information that is presented by the view. Such editors may be spliced into the path between the controller and its view, and will act as an extension of the controller. Once the editing process is completed, the editor is removed from the path and discarded.

Note that an editor communicates with the user through the metaphors of the connected view, the editor is therefore closely associated with the view. A controller will get hold of an editor by asking the view for it - there is no other appropriate source.

1
  • It is full of run-on sentences. Jan 17, 2021 at 8:32
11

MVC is a design pattern used to isolate business logic from presentation.

It differs from a lot of other design patterns by the fact that it usually isn't implemented succinctly, but is the base of a framework.

While an application implementing a Strategy pattern is just a small detail about it, saying that a web app uses the MVC design pattern is very defining of its architecture.

1
  • 3
    That's not strictly helpful, there are very specific requirements to implement the MVC pattern which make it differ from MVP, MP, MVVM. It also has a different target audience to those other presentation patterns.
    – Ian
    Dec 30, 2011 at 12:43
8

MVC is a software design that separates the following components of a system or subsystem:

  1. Model - Data about the state of the application or its components. May include routines for modification or access.
  2. View - An interpretation of the data (model). This is only limited to a visual representation, but could be audio, derived information (e.g. statistics piped into another model object), etc. Furthermore, a single model may have multiple views.
  3. Control - Handles external input to the system invoking modifications on the model. The control/view may be closely related (in the case of a UI). However, other external input (such as network commands), may be processed which are completely independent of the view.
6

I would say MVC is a concept or a family of similar patterns.

I think this article is worth to read. GUI Architectures by Martin Fowler

1
  • 5
    That Fowler article is excellent, and everyone who uses the term MVC should read it. Two points I find particularly interesting are that the original use of the term MVC in GUIs is rather different to the use in web frameworks, and that in GUIs, the separation between view and controller was found to be less useful than anticipated. Oct 21, 2012 at 22:38
3

First, you have to determine who the asker of the question is, and what sort of answer he's looking for. You respond to this question with another question, such as "In what sense?"

You can ask if they are referring to MVC in general, a particular implementation of MVC (ie asp.net MVC, spring MVC, smalltalk MVC, etc..), what it is technically, what it is philisophically (yes, it has a philosophy as well), etc..

If this is a question on a test, and you can't ask the asker to clarify, then you will have to guess based on the context.

A good, simple answer is:

MVC is a software user interface architecture used to seperate structural and behavioral concerns in order to facilitate more maintainable sofware.

You can also say:

By seperating the View from the Controller from the Model, it encourages isolation of components based on their responsibilities. In theory, and usually in practice, this helps to improve maintainability by preventing the different parts of the system from co-mingling and creating more complex systems.

But, in the end, you will be judged on whether you give the answr they are expecting. The only solution to the problem is find out what kind of answer they are expecting.

2

Here is what I would say about it. I would try to explain it in terms of mobile applications, because it is what I am most familiar with and because I don't think I fully understood it before started doing mobile applications.
Let's take Android for example.
Presentation layer, ie. user interface can (should, most often is) be specified entirely in xml. For simplicity, let's say that one xml file describes one screen in the application. XML file specifies controls, layout of the controls, positioning, colors, size, string labels... everything regarding presentation. Yet it knows nothing about when it will be called, when will it be placed on the screen. Will it be a stand-alone layout or a part of some bigger layout? There you have it: your perfect VIEW.

Now, view obviously needs to be placed on the screen at some point, so how should do it? Your CONTROLLER, in Android called Activity. As the name says, activity does some activity. Even if its sole purpose is to display view defined in step 1, it will perform some action. So, activity fetches a view and displays it on screen. As view does not know nothing about activity, similarly activity knows nothing about the actual presentation. We (the programmers) could rearrange the layout of the view multiple times, without changing even one line of code in our activity.

Now, there is not much use in presenting your nice shiny, well-defined xml layout without actually doing something. Let's say we want to store the data entered by the user. Activity needs to tackle this process from taking the data from the user to passing it on to someone else to handle it (process, store it, delete it). Who will it pass to? Well, to a MODEL. I like to think of a model as a pure .java class that knows nothing about application context it lives in. (In practice that will almost never be the case).

Let's say I have a class Person that has three properties: name, address, age. My XML defined layout has 3 fields for user input: name, address, age. My activity takes the three values from user input, creates a new Person object and invokes some method on it that knows how to handle some Person-specific logic. There you have it. Model-View-Controller.

1

I always start off by telling them that the pattern is not anything new and has been around for many years... its at this point they give me an inquisitive look and BAM!, they are hooked:

And then I would pretty much talk about the various points like the previous answers, but I think its important to be contextual as well, as JB King said, ASP.NET MVC etc,

Not the answer you're looking for? Browse other questions tagged or ask your own question.