Model View Controller

An easy way to understand MVC: the model is the data, the view is the window on the screen, and the controller is the glue between the two. -- ConnellyBarnes

The best rubric ever: "We need SMART Models, THIN Controllers, and DUMB Views"

The Controller does not oversee the operation of the Views and Models - it's not a GodClass. The controller mediates communication and unifies validation, using either direct calls or the ObserverPattern.
Model-View-Controller is the concept introduced by Smalltalk's inventors (TrygveReenskaug and others) of encapsulating some data together with its processing (the model) and isolate it from the manipulation (the controller) and presentation (the view) part that has to be done on a UserInterface. Smalltalk provides mechanisms to link models, views and controllers in some standard way in order for a model to communicate state changes to every attached view (there can be several, as you can see). Model state changes happen either because a controller issued some command or for some internal reason.


Note that the term Controller has adopted two radically different meanings - see WhatsaControllerAnyway. Also see MartinFowler's PatternsOfEnterpriseApplications?, who bemoans this greatly.
A triad of three modules linked by the ObserverPattern, all residing within a RepresentationLayer. The View drives a presentation within a GuiLayer, and elements within the View observe the Model. Elements within the Controller observe the View and Model, and elements within the Model observe the Controller. The Model fronts data objects within the LogicLayer.

This pattern decouples changes to how data are manipulated from how they are displayed or stored, while unifying the code in each component.

Alternative versions of this pattern appear in many architectures, and with various layer affiliations. Simplifications include Observing an entire component instead of elements within it, and using direct method invocations instead of Observation messages. Complications include substituting any element of the three components with another one.
I've started writing a history of MVC at ModelViewControllerHistory. -- MitchellModel

On ModelModelViewController I've highlighted that since the early days of Smalltalk MVC there have usually been two models involved. -- RandyStafford
Derivations & extensions to MVC


When a system obeys the principle DoTheMostComplexThingThatCouldPossiblyWork, marketects often respond by clumping its rambling notions together into 3 groups. The sub-SpaghettiCode group nearest the User becomes the "view", that nearest the database becomes the "model", and the stuff in between becomes the "controller".

Marketects then refer to their project's architecture as "MVC", borrowing that acronym's impressive lineage.

Sounds like SunMicrosystems's JavaLanguage PetStore

- True, but the remarks concerning 'marketects' actually goes for the whole branding of MVC, which we refer to in our shop as ModelViewCrapola?. There are usable concepts in the MVC idea, but we find it is an ossified model too often imposed, especially in web based apps. -- LlewelynThomas
Is MVC a pattern? Several patterns? I propose an MVC pattern contest (either here or for PLoP). Ideas on how to proceed? This could be fun. -- JimCoplien
How does the more recent DocumentView architecture (presented in some windowing platforms) differ or resemble the older MVC? -- SkipSailors

They are similar in a way such that: -- ChaoKuoLin
MVC means many things to many people. That's why there will be many patterns with at least a connection to MVC. One of the last things we did in MondaySchool was to have a go at browser patterns (st-80 style browsers). I think they would count as MVC patterns too. Anyway, with that much latitude allowed, here is the list... On the other hand, AdeleGoldberg maintains that MVC is the solution to one specific problem and therefore just one pattern (though I doubt she would use the term.) She would say:
Not all people can or prefer to operate a computer in the same way.
Therefore, separate the controls of the computer from the views it presents so that appropriate controls can be selected by the user. A handicapped individual would be an example of a user needing a different kind of control.

I don't know of specific examples where this MVC capability has been exploited. Do you? -- WardCunningham

Perhaps web pages are an example of this - with the 'view' being css, 'model' being html, 'control' being, in part, the browser. I agree on this. I think javascript could be seen as the controller-part of the web-page. This becomes very apparent with Microsoft's lesser-known extension called behaviours. Behaviours are basically a declarative way of linking javascript code to styles (the view). Does anybody have any links on this perspective?

I'm not sure if it would be applicable, but Amiga programs used to widely support an AREXX "port" which allowed programs to be controlled through the REXX scripting language, basically by another process. Thus the user interface presented one view, and events therefrom constitute one "controller" while events from the AREXX port would seem to be a different "controller" (and return values from control events would presumably represent another view as well).

In this way, I'm a little unclear about why MVC separates V and C. If we think of VC (taken together) as "interface" then the whole MVC approach seems to simplify to ModelDelegate or client/server (or more formally, client - protocol - server). Does abstracting the controller somehow facilitate inter-object interactions? Does it make sense that some controls don't have a corresponding view, or is it that some controls may have to affect several views some of which don't offer any user interaction (and thus don't implement the control aspect of an "interface")?

What about SqueakSmalltalk's alleged handwriting recognition? I have not actually used it, but... -- BillTrost

Real-time audio apps do this. (Ardour for example). The controls are not the primary view, the audio output is, and we do not control the app with audio, but we may control it with two separated input controllers, a gui and perhaps a hardware interface over midi. Also, in well-designed ones, the controllers are never allowed to jam the output, so they must be properly separated with some kind of queue to the model. So we wind up with an engine (model) that receives input from more than one control interface, but outputs a 'view' that is never tied in with controls. The view is notified whenever a model state changes. In the case of a gui, that too needs to get updated as a secondary 'view' but the hardware controllers do not. -- Iain Duncan
I can think of one instance I've seen. Back around 1992 EricSmith was asked by one of our clients to build a VT-100 interface to some Smalltalk (ObjectWorks 4.0) code. He did it by defining a VT-100 GraphicsTool? and a set of special-purpose Controllers for VT-100s (ListController?, ParagraphEditor?, etc.) that would translate keystroke combinations into the equivalent of mouse-moves. In this way his browsers would work the same on the workstation AND on the VT-100. -- KyleBrown
Like the original MVC article's title - "A Cookbook for Using the Model-View-Controller User Interface Paradigm in Smalltalk -80" (Glenn Krasner and Stephen Pope, JournalOfObjectOrientedProgramming, August/September 1988, http://www.ics.uci.edu/~redmiles/ics227-SQ04/papers/KrasnerPope88.pdf) - says, it's a paradigm. It's a conceptual framework for designing and implementing graphical user interfaces. A class library, such as Smalltalk-80's, would typically implement MVC based on abstract classes and default method definitions for models, views, and controllers - a Framework! -- MitchellModel

"A Cookbook for Using the Model-View-Controller User Interface Paradigm in Smalltalk -80" is not the title of the original MVC article. A publication from 1979 by Trygve Reenskaug shows that the idea of MVC is much older: http://heim.ifi.uio.no/~trygver/1979/mvc-2/1979-12-MVC.pdf. -- TimoStamm?
A link to a decent explanation of MVC would be welcomed here. After spending a few hours searching today, I come home empty handed...Let me know if you have something please.

I found http://ootips.org/mvc-pattern.html to be useful. -- JohnClonts

Ward's collection of HotDraw CRC cards (http://c2.com/doc/crc/draw.html) helped me wrap my mind a little further around the concept.
I think that Model-View-Controller is good as far as it goes, but that some expansion of the concepts are needed. The development of JavaSwing provides some clues, I think.

I'm offering ModelPipeViewController for consideration, and would appreciate some feedback.

-- BruceAtherton
Apple's tutorial for Rhapsody - Discovering OpenStep - provides detailed examples of the MVC model, and a description of it.

Chapter 2: A Simple Application provides a description, and Chapter 4: A Multi-Document Application probably provides the best example of the benefits. -- RonaldHayden
ModelViewPresenter tries to solve some of the drawbacks of mvc. What do the experts say? -- ThomasMahler

-- IanChai
WebMacro implements a ServletDesign based on Model/View/Controller. The argument is that, because the web works by returning HTML views to clients, an MVC design is inherent in server-side web programming. Java servlets, unlike CGI, make it more of a reality because they persist between connections and are most likely to have a middle-tier model underneath them. WebMacro is a free servlet framework that implements this ServletDesign. -- JustinWells

By the way, what is MVC2 in the servlet context? Why MVC1 was not enough and how does it differ from the original MVC? -- GuillermoSchwarz
I had an interesting chat with TrygveReenskaug this week. He notes that the original MVC had four objects: not only the model, view, and controller, but the user as well. He regrets that the fourth object has become lost in the popularization of the idiom.

He notes that MVC was an outgrowth of the original direct-manipulation metaphor popularized in early OO practice (see BrendaLaurel's ComputersAsTheatre), where you want the objects on the screen to be the objects in the program. MVC actually works against that metaphor but evolved as a necessary evil. Why? Because the user object maintains multiple simultaneous views of the model at once; the factoring into user, model, view, and controller allows one to support that. So while the speculation is that Adele would approach MVC from the input side, Trygve approaches it from the output side.

...which discussion of direct manipulation segues nicely into: MorphicInterface. In SqueakSmalltalk this is (apparently) replacing the MVC framework (not paradigm!). As someone else comments on the MorphicInterface page, there is very little information around on it. Despite having read Mark Guzdial's book on Squeak and the original papers on Morphic in the SelfLanguage I am none the wiser if there is really anything useful to be learned here (is it really an alternative way to structure programs than MVC?). Help me Obi wan, you're my only hope...
I've been trying to apply some of the ideas behind XP and the refactoring thing in VB, but am at a bit of a loss with MVC. Can anyone provide some simple examples?

See ModelViewControllerInVbClassicActiveServerPages.
The comment by TrygveReenskaug quoted above fits nicely with the way I like to think about MVC: I wouldn't push that too far, but it sometimes help me sort out design issues.

-- Don Dwiggins
One could make the case that MVC is more general than a user interface pattern. The user might be another piece of software (class). It would therefore include FacadePattern, VisitorPattern et al. -- TomRossen
Has anyone had much success with ModelViewController and the PalmOs? -- ScottElliott
MVC is exactly the same as BASIC. Let me explain! In BASIC you had INPUT, PRINT and LET and most of the code was just assembling them together, but your code written this way could not be assembled together. - This is completely incorrect. MVC is quite the contrary! If we apply that logic to any language able to accept input, process it, and generate output (that is, ANY computer language), any computer language would be the same as MVC. A computer language is used to implement the MVC pattern, but that doesn't make it a pattern language. Is like saying that brick and mortar is a house: in fact, a house is a pattern that can be built with brick and mortar, but that doesn't mean that a house is brick and mortar... it is the way brick and mortar are assembled what builds a house. -- LuisColorado

Then somebody realized that code should be organized the same way: Input, Output and internal processing. I/O was called the View/Controller and the internal processing was called the Model. Incorrect: in fact, the Model, the View, and the Controller are objects able to receive input and to provide output to the other components. -- LuisColorado

That is why Servlets are not MVC, nor Struts is MVC, nor J2EE is MVC. How do you know there are not? Because in MVC when you change the model, you don't need to change the view, since it is updated automagically. MVC is about direct manipulation of objects, they know how to display themselves, and because of that, the smaller objects must know how to display themselves. Big objects are made of smaller object that know how to display themselves, so big objects magically know how to display themselves. This is partially correct. I don't know of any language or technology that per se enforces MVC, and that includes J2EE, Servlets, etc. Another correction: in MVC, the Model objects don't know how to display themselves, neither have object that know how to do so. You are referring to the View objects. -- LuisColorado
The essential ingredient in MVC is the Observer pattern. Take that out and all you have left is IPO (Input-Process-Output). The Observer is what maintains encapsulation and keeps MVC strongly object-oriented. Without the Observer, you need setters and "this object here fiddling inside that object there" - decidedly non-OO.

Any software architecture that features three components or layers will eventually be described as an instance of MVC. Then it will be criticized for doing it wrong.

-- MarcThibault
ModelViewController is one of the few design patterns to have been turned into a song: http://home.in.tum.de/pittenau/ModelViewController.mp3 (lyrics at http://www.oreillynet.com/pub/wlg/3533). That fourofoured for me. Alt location: http://vst.ensm-douai.fr/noury/20
Historically MVC patterns could have been promote as to allow magical switch of views around the same model or models around same view. Also many implementation library/tools had a design to facilitate composite of different MVC.

In fact for the MVC pattern the idea of model and view switching requires that the substitute view or model have the exact same interface with the controller than the original view or model otherwise the magical switch is broken. Change just one thing as a little different view dynamic behavior or one missing model method and the magical switch is broken.

Also in the MVC pattern there's absolutely no design to have composite MVC.

From this point of view you can design view as jsp with JavaBean views, Action as controller and models as JavaBean models to have a MVC pattern. That's enough to support the weak and too simple MVC pattern. -- BernardDevaux?
I've occasionally found MVC-ish patterns cropping up in my code more or less spontaneously; most recently in a small computer game. The model knows something's stats and location, the view knows how to draw on the screen, and the controller is particularly flexible, being the interface between a game object and the user... or the AI... or a network connection... or a limited-purpose AI like an autopilot...

Neat stuff.

-- SimonHeath
Computer Graphics Principles and Practice by Foley, van Dam, Feiner, Hughes (ISBN 020184840-6 ) presents an interesting description of the ModelViewController concept on pages 17 to 22. -- ChrisEineke
Links:
TestDrivenDevelopment gripe: Testing is about isolation and decoupling. But most out-of-the-box MVC platforms force you to test the Controller by drilling down from the View, thru the whole stack. WTF? -- PhlIp

That is why I generally like to keep listeners (in Java) as external classes. They can then be instantiated along with the other objects necessary for testing. While you don't test the View, you can then fire events and ensure you are getting the right behavior.

-- Brad


I think the problem is that the semantics were wrong from the get-go. We commonly talk about data models and that clearly isn't what is meant here. To have application logic running in a model conflates the two definitions of model. In reality we want something similar to View-Listener-Logic-Data Model. In Java data models are termed 'beans' (I hate the cutesy term). Using them helps with serialization and testing. It is easy to mock one and stuff data into it. Using just Logic-Data Model-Listener one can do full development of the data models and application logic. Those can then be run as part of the daily build. It also ensures that the application logic and data model are not coupled to a specific View-Listener type.

-- Brad
This phrase seems stuck in FuzzVille because everybody is using a different head-model for stuff. Could somebody propose an algorithm or unambiguous list of rules for categorizing or "slotting" a given piece of code or algorithm into one of the three categories (model, view, controller). Something along the lines of, "if it has X or does Y, then it's a controller. If it lacks A, B, or C; and Q, then it's a model", etc.

More specific rules are not needed, as it's a general pattern.

"Data" is a vague term. I want to avoid IknowItWhenIseeIt. And by "visualization", do you mean UI? If so, MVC is trivially common and there are no real alternatives other than raw RAM data or RAM dumps. Perhaps what is needed is a contrasting model(s) to see what MVC is not.

Something less vague than "data" is unnecessary. By "visualisation", I typically (but not exclusively) mean UI, and MVC can be found frequently enough to be considered common. However, explicit awareness of it allows us to construct classes, frameworks, etc., that facilitate it. As for seeing what MVC is not, that's somewhat difficult -- it's a bit like trying to define "musical instrument" by seeing what a "musical instrument" is not.

Present a truck; it's a start, and better than what we have so far for MVC. (Granted, a truck can make [poor] music, but is a rare demand of it.) Most non-electric musical instruments fit into known categories, such as wind, string, percussion, etc. We can have check-lists of features for them and add up scores/weights to come up with a "fitness" score.

There are numerous examples of MVC on the Web. See, for example, http://www.codeproject.com/Articles/25057/Simple-Example-of-MVC-Model-View-Controller-Design

Okay, but where are the examples of non-MVC for contrast? One cannot tell from such examples alone whether the elements of the example are required for MVC, or just a byproduct of the example.

Here's a Tiny C compiler: http://bellard.org/tcc/ There's no model, no view, and no controller. It's not MVC.

Okay, but what's missing that makes it non-MVC? It has working variables and data structures that could perhaps be called a "model", and the output (machine language) the "view" without some clear rule to disqualify them.

For one thing, it's not interactive. MVC is typically used to manage interactive manipulation of data. The compiler's "model", once created, does not change and is not intended to change so there is no interface to the model to support interactive change. MVC supports at least the potential for multiple views but the compiler has -- at best, and stretching the usual definition of "view" -- just one. There is nothing in the compiler that could be considered a controller. On the other hand, an interactive programming environment (e.g., Logo, TomatoIde, etc.) likely uses MVC if the internal representation of the program (i.e., model) is intended to change.

We can make it interactive, such as, "A loop of pattern X was found at line 123. Do you want to optimize it for a single core or multi-core?". And what do you mean by "multiple views" in the compiler example?

If we make it interactive, then MVC might be an appropriate way to handle the interactivity. By "multiple views", I mean that there aren't various ways of viewing the object code built into the compiler.

But how about we try to stick to GUI's for analysis. Is there a common (or once-common) GUI model that is clearly not MVC?

Sure. A trivial input-process-output loop is not MVC. There is no "model" to abstract a collection of discrete variables, though you might glancingly consider a data-entry form to be both view and controller -- which it is, to the same degree that a truck can be considered a musical instrument.

I'm still not clear on this. Please elaborate on "to abstract a collection of discrete variables". Variables and collections are already abstractions.

By "collection", I meant "a bunch", not an explicit Collection mechanism.

With sufficient effort, I'm sure you can argue that everything is MVC and nothing is MVC, but that would be as pointless as arguing that there are no distinctions between things and everything's just stuff. If you are genuinely having difficulty identifying or grasping MVC and are sincerely interested, I'll point you to some resources. Otherwise, I have better things to do than teach you intermediate-level OO programming.

The pattern(s) is ill-defined and the term is overloaded, that's my main point. Perhaps one can say, "This is the Fred GUI Model or framework 2.0", and eliminate mention of models, views, controllers, etc. It would eliminate a lot of industry confusion.

It's ill-defined or overloaded only if you're expecting MVC to be represented in a definitive fashion, such as by a specific DesignPattern. MVC is best regarded as a general architectural approach, implementable in numerous ways. As terminology, "MVC" is on par with notions like "musical instrument" or "swimming", which are general concepts having innumerable manifestations. There's only "industry confusion" (perhaps) when talking about MVC, as some folks naively get hung up believing there is a "true MVC" and others that are not, but there's no real confusion when implementing or using it -- in the end, it just turns into code.

It may be helpful to regard MVC as the interactive analogue to the classic batch-oriented input-processing-output model of non-interactive programs. The model contains the program state, the view displays the model to the user, and the controller receives input from the user to change the model.

As rough labels for very general notions, perhaps. And musical instruments have pretty good sub-classifications associated with them. Nothing comparable exists for MVC.

Nothing comparable needs to exist for MVC. It's clear enough for the purpose.

It needs work.

What needs work? Developers are effectively using and implementing MVC on a daily basis. Definitions -- largely in agreement -- can be found in numerous places. This seems to be a non-problem for everyone but you.

Of course they are, there is no real alternative. One would have to go out of their way to NOT use it, based on the way it's described here. It's a UselessTruth. Stop trying to defend rubbish.

Clearly, you have not read any of the above. Again, this seems to be a non-problem for everyone but you.

I tried, but it's nebulous. And other developers do confuse the term. The other wiki topics debating the term and its application are a testament to this. I didn't create those topics.

Debate does not imply confusion or misunderstanding; it only implies disagreement.

Yes, disagreement over the meaning of the term and/or terms of its parts.

They're quibbles amongst the knowledgeable, like arguing whether a V4 engine is better for racing than an I4 (or vice versa) amongst engineers. It's not the "I don't get it, so the explanation must be wrong or it doesn't exist" that you consistently maintain.

I'm asking for a clear and concise definition (or at least a reasonable attempt at one), not resume evaluations. Different issues. The topics of the "experts" on this wiki are also struggling with the term.
Almost all computer games exhibit a very clear MVC, with a literal controller which is physically separate both from the view (ie, TV or monitor) and the modelling unit (the CPU/box, with its internal representations of the game components).

It's mainly in the realm of touch-devices like phone UIs that the view and controller become blurred. Even on desktop computers, the reality is that the keyboard and mouse are the controllers and the "controls" on the screen are actually views, so that often there are two views showing different aspects of the model. For example, a slider "control" might be a view onto a movie file, while the display of an individual frame on the same screen is really also a depiction of the current point in the playback. But, in reality, the controller is the mouse that clicks "pause" or the keyboard that transmits the shortcut for "rewind".

TWW
Top's Working Definition

I've selected this definition set in part because the "parts" are relatively unambiguous and not tied to any particular language or paradigm. Perfect non-ambiguity is probably not possible.

Note that it is possible to combine Model and Controller, such as a UI manager that is integrated or closely tuned around a specific domain. An example would be a gaming rendering engine that has a texture library manager built-in (so that a gaming shop doesn't have to invent their own). For the most part, shops will use an existing GUI manager that was designed independent of their particular domain, and one can potentially examine the history of the Model and Controller to see if there is any cross influence.

Under this definition, there is no such thing as a "non-MVC" framework. MVC is just way to describe the parts of systems that have significant UI's.

-- top

That's an entirely reasonable definition and assessment. I'd only change "... that have significant UI's" to "... that have significant interactive UI's".

If you call anything that Toppie presents as "reasonable", you'll get flogged around here :-) As far as "interactive", a non-interactive app or system may also have the 3 parts and it may also be useful to make a distinction between the 3 parts. For example, CrystalReports (CR) often functions as the "Controller" portion of a batch reporting system/app. The Model is the data tables and the CR user's (report programmer's) report configuration that set up the definition of the report in CR. The View is the printed output or output document file. [Reworked wording.] -t

I'm not clear how CrystalReports is MVC. Could you explain? By the way, your usage of Controller is acceptable, but not quite conventional. By convention, the Controller provides an interface to update the model and (indirectly, but sometimes directly) the view.

We could say it only applies to interactive systems because that's where the term was born. But I'm not sure it's useful to so narrow it nor problematic to keep the wider version (where input or interaction is optional).

I don't see how that answers my question, or how it addresses my comment about your definition of Controller.

I didn't say CR "is" MVC, only that it often acts as a controller in a batch process in organizations because it "translates the Model to the View". As far as your comment, I thought I addressed it adequately. I don't understand the complaint.

I see. When you wrote, "a non-interactive app or system may also have the 3 parts [...] For example, CrystalReports is the 'Controller'", I thought you meant that CrystalReports has all three parts and you used Controller as an example of one of them, and that it is, therefore, MVC.

I shall rework it to avoid that interpretation path.


To Define this alleged ModelViewController, one needn't look further than Qt's QTreeView & model system, or RubyOnRails' lexical first approximation which can do no wrong. ~~Him that thou knowest thine


See: WhatsaControllerAnyway, DesignPrinciplesBehindSmalltalk, ModelModelViewController, ApplicationController, ModelViewControllerAsAnAggregateDesignPattern, ModelTargeterSurface, MvcVersusEventDriven, MongrelEeRuby, MirrorModel

Contrast: MvcIsNotObjectOriented, MvcIsNotImplementable, TestFixture, CommitRollbackDatabaseAutoTests

CategoryPattern, CategoryUserInterface

EditText of this page (last edited November 20, 2014) or FindPage with title or text search