Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I understand the role of the model and view in the Model-View-Controller pattern, but I have a hard time understanding why a controller is necessary.

Let's assume we're creating a chess program using an MVC approach; the game state should be the model, and the GUI should be the view. What exactly is the controller in this case?

Is it just a separate class that has all the functions that will be called when you, say, click on a tile? Why not just perform all the logic on the model in the view itself?

share|improve this question
1  
Personally, this is what I do. There may be cases where there is no alternative to MVC, but I can't stand it. –  Mike Dunlavey Mar 27 '12 at 22:53
9  
Three words..."Separation Of Concern". –  Travis J Mar 28 '12 at 0:19
3  
Almost all Windows programs before .net used Doc-View with no controller. This seems to have been relatively successful. –  Martin Beckett Mar 28 '12 at 15:17
    
Martin, un(change)able monolites. –  Independent Aug 23 '12 at 17:07
    
I've answered below, but I'll add that yes, you can build an application without distinct controller classes, but that wouldn't be MVC. You're assuming "an MVC approach", so yes, controllers play an important role. If you choose some paradigm that's not MVC it's quite possible that you won't have any controllers. –  William Shakespeare Mar 25 '13 at 14:22

11 Answers 11

up vote 4 down vote accepted

Using your example the Controller would be what decided what was a legal move or not. The Controller would let the view know how to arrange the pieces on the board at start up using the information it received from the Model. There are more things that can be handled by the Controller but the key is to think about Business Logic on that layer.

There are times when all the Controller does is pass information back and forth, like a sign up page. Other times the Controller is the difficult part of the development because there are many things that need to be done at that layer like enforcing rules or doing complicated math for example. Don't forget the Controller!

share|improve this answer
29  
"Using your example the Controller would be what decided what was a legal move or not". This is bad example :( such logic shall be also in the Model. Otherwise your logic is split between Controller and the Model. –  Dime Mar 29 '12 at 9:26
6  
@Dime - The model should contain no logic whatsoever. The Controller will be the one holding logic, hence "controlling". –  Travis J Mar 29 '12 at 11:40
31  
@TravisJ Don't quite agree there. Controlling doesn't mean knowing how to do a job. It is about controlling those objects that do. Hence the logic for doing the work would be in the model and the controller would control which model to use to perform the necessary requirements of the action etc Too much logic in controllers in my view would be recipe for controller blot... –  dreza Mar 31 '12 at 22:25
22  
The whole point of OOP is to have cohesive bits of data and behavior kept together and state internally encapsulated. "Model" models both behavior and data. –  Chris Aug 22 '12 at 20:45
10  
-1 The controller must not contain business logic. The model is "the app", it holds the data and has callable routines for everything that can happen in the app; not necessarily all in one file or class. The view visualizes the state of the model. The controller bridges the model/view and the real world/input. Want to "publish" the app as a web app? Just need a controller that handles HTTP and an appropriate HTML-based view. Want a command line interface to your app? Just need an appropriate controller and view. The model, the business logic, never changes in these cases. –  deceze Mar 24 '13 at 22:34

Why not just perform all the logic on the model in the view itself?

The controller is the glue that binds the model and view together, and it's also the insulation that keeps them apart. The model shouldn't know anything about the view and vice versa (at least in Apple's version of MVC). The controller acts like a two-way adapter, translating user actions from the view into messages to the model and configuring the view with data from the model.

Using the controller to separate the model and view makes your code more reusable, more testable, and more flexible. Consider your chess example. The model would of course include the game state, but it might also contain the logic that affects changes to the game state, such as determining whether a move is legal and deciding when the game is over. The view displays a chess board and pieces and sends messages when a piece moves, but it doesn't know anything about the meaning behind the pieces, how each piece moves, etc. The controller knows about both the model and the view as well as the overall flow of the program. When the user hits the 'new game' button, it's a controller that tells the model to create a game and uses the new game's state to set up the board. If the user makes a move, the controller relays the command to the model and, based on the response, allows the move or not.

Look at what you get by keeping model and view separate:

  • You can change the model or the view without changing the other. You may have to update the controller when you change either one, but in a way this is part of the advantage: the parts of the program that are most likely to change are concentrated in the controller.

  • Model and view can both be reused. For example, you could use the same chess board view with an RSS feed as a model to illustrate famous games. Or, you could use the same model and replace the view with a web-based interface.

  • It's easy to write tests for both model and view to ensure that they work the way they should.

  • Both model and view can often take advantage of standard parts: arrays, maps, sets, strings, and other data containers for the model; buttons, controls, text fields, image views, tables, and others for the view.

share|improve this answer
2  
+1 You nailed it. –  David Harkness Mar 25 '13 at 5:50
    
In the original MVC architecture for desktop applications, views were active classes, observing the model directly, and disconnected from the controller. –  kevin cline Mar 25 '13 at 17:57
    
The problem with all the answers is that there are as many interpretations of MVC as people posting. And the benefits listed above only apply to one specific interpretation of MVC. If one were to put most of the logic into the controller (or model) and have the View call/initiate specific method calls on the controller then that makes the Controller/Model combo standalone and very reusable. Most of the time it is a new view that is needed. I have never had a need to reuse a view. Even your RSS example could be easily handled with a new View that uses your old one with an RSS layer in between. –  Dunk Mar 25 '13 at 23:03
1  
@Dunk: it is vital to separate the business logic from the user interface so that the business logic can be tested directly. –  kevin cline Mar 26 '13 at 20:48
1  
@Dunk: I suppose you can call anything you like a "controller", but in the MVC architecture, the controller is dependent on and therefore part of the user interface. –  kevin cline Mar 27 '13 at 17:06

There are many, many different ways of implementing this general design pattern, but the basic idea is to separate the various concerns as necessary. MVC is a nice abstraction in the sense that:

Model: Represents that data, whatever that might mean
View: Represents the user interface, whatever that might mean
Controller: Represents the glue that causes that model and view to interact, whatever that might mean

It's extremely flexible because it doesn't specify a whole lot. A lot of people waste a lot of bandwidth arguing the details of what each element might mean, what names should be used instead of these, and whether there should really be 3 or 2 or 4 or 5 components, but that's missing the point to a certain degree.

The idea is to separate out the different "chunks" of logic so that they don't overlap. Keep your presentation stuff together, keep your data stuff together, keep your logic stuff together, keep your communication stuff together. And so forth. To a certain extent, the less these areas of concern overlap, the easier it is to do interesting things with them.

That's all you really should be worrying about.

share|improve this answer
3  
Glue, glue, I like that definition, it's so correct: the whole model should be christened MVG and people would stop scratching their heads in search of elegance where there isn't any to find. –  ZJR Aug 22 '12 at 20:11
    
+1 for “glue”; it also means that it is the part that is best suited to being done in a scripting language (as those tend to excel at gluing). –  Donal Fellows Mar 25 '13 at 8:54

All good answers so far. My two cents is that I like to think of the controller as primarily being built up with questions like What and where?

  • I've been asked if a chess piece (view) can be moved to x. Is it
    allowed? I'm not sure but I know where and who to ask (the model).
  • Something has asked me to save my data. How the heck do I do that? I know where to ask though! How we save the data, or where it's saved to, I've got no idea, but that Repository class should know. I'll forward it and let it deal with it.
  • I've got to show the current chess piece position to the user that the model moved it to. not sure if I want to show the piece as green or yellow? Bah, who cares, I know there's a view that can handle this so I'll pass em the data and they can decide how it's going to be showen.

These little snippets are examples of how I'm trying to remember the abstraction and concept MVC is trying to convey. What, Where, and How are my three main thought processes.

What and where => Controller How and when => Models and views

In essence my controller actions tend to be small and compact and when reading them tend to look sometimes like a waste of time. In closer inspection they are acting as the traffic signal man, channeling the various requests to the appropiate workers but not doing any of the actual work themselves.

share|improve this answer

A Controller could help abstract the interfaces of both the View and the Model so that they don't have to know about each other directly. The less an object has to know, the more portable and unit testable it becomes.

For instance the Model could be playing another instance of itself thru one Controller. Or a networked Controller could connect two player's Views objects together. Or it might be a Turing test where nobody knows which.

share|improve this answer
    
+1 for Turing test. –  msanford Aug 22 '12 at 21:11

It really comes into play when you are dealing with event handlers, but you still need the controller to handle interactions between the view and the model. Ideally you don't want the view to know anything about the model. Think about it, do you want a jsp to make all the database calls directly? (Unless it's something like a login lookup.) You want the view to render data and not have any business logic, unless it's view rendering logic, but not business logic perse.

In GWT, you get a cleaner separation with MVP. There is no business logic whatsoever (if it's done right) in the view. The presenter acts as a controller and the view has no knowledge of the model. Model data is simply passed over to the view.

share|improve this answer

I think MVC is dumb, maybe in specific areas it works well but personally even websites i write are not suited to mvc. Theres a reason why you hear frontend, backend and never database-end or something-else-end

IMO there should be an API (backend) and the app which uses the API (frontend). I guess you could call the GET request the controller (which simply calls the backend api) and the html the view but i don't usually hear people talking about view as pure html nor model being backend API.

IMO everything should be a solid API. Actually they don't need to be solid (as in clean and well built) but its internals should remain private and the app/frontend/outside of the api should never get say the database connection nor be able to make raw queries.

Now if your code/design involves glue its fine. If in your chess game there is some markup you can edit to skin the GUI, the gui collects the coords/input and calls MovePiece(srcPosition, dstPostion) (which may return a bool or enum to say if it is a valid move or not) and your ok with all logic being in the model then sure call it MVC. However i'd still organize things by classes and APIs and make sure theres no kitchen-sink class that touches everything (nor any APIs to have to know about everything).

share|improve this answer

I understand the role of the model and view in the Model-View-Controller pattern, but I have a hard time understanding why a controller is necessary.

Are you sure about that?(At least as originally described) The point of the model is to be the domain model. The view is supposed to display the domain model to the user. The controller is supposed to map low level input to high level model speak. As far as I can tell the reasoning is something along the lines of: A) a high level use of the SRP. B) The model was considered the important part of the app so keep the unimportant and faster changing stuff out of it. C) easily testable (and script-able) business logic.

Just think if you want to make your Chess program useable by the blind, swap out the view for a audible version, and a controller that works with the keyboard. Say you want to add games by mail, add a controller that accepts text. Net version of the game? A controller that accepts commands from a socket would do the job. Add a nice 3d render to it, a cool new view. Zero model changes necessary Chess is still chess.

If you mix input in with model representation then you lose that ability. Suddenly Chess isn't Chess, it is Chess with a mouse which is different from Chess with a keyboard or network connection.

share|improve this answer

Document-View (ie model view) is the standard model for the majority of Windows apps written in MFC so it must work for a lot of cases.

share|improve this answer

Think of a browser that displays a static web page. The Model is the HTML. The View is the actual result on the screen.

Now add some JavaScript. That is the Controller. When the user clicks on a button or drags something the Event is sent to the JavaScript, it decides on what to do and alters the underlying HTML (Model) and the browser/renderer displays those changes on the screen (View).

Perhaps another button is clicked, the event is sent to some handler (Controller), and it may cause a request for further data to be sent to a webservice. The result is then added to the HTML (Model).

The Controller responds to events and controls what is in the Model and hence what is on the screen/View.

Stepping back a bit, you can think of the whole browser as the View and the server as the Controller and the data as the Model. When the user clicks a button in the browser the event it sent to the server (Controller), it gathers together resources as an HTML page (Model) and sends that back to the browser to be displayed (View)

Down in the server whether it is asp, php, or java the 'code' (Controller) receives the click event and queries a database or document repository (Model) and creates HTML. From the server point of view the result of all its actions are a View (HTML) of its underlying datastore (Model). But from the client point of view the result of its request to the server is its Model (HTML)

Even if you jumble up your JavaScript in your HTML or your PHP in your HTML the Model, View, Controller still exists. Even if you think of your request to a server and the response back from the server as a simple two way street, there is still a Model, a View, and a Controller.

share|improve this answer

In my experience, in a traditional desktop mvc gui program, the controller ends up spaghettied into the view. Most people do not take the time to factor out a controller class.

the gang-of-four book says:

Design Patterns in Smalltalk MVC

The Model/View/Controller (MVC) triad of classes [KP88] is used to build user interfaces in Smalltalk-80. Looking at the design patterns inside MVC should help you see what we mean by the term "pattern."

MVC consists of three kinds of objects. The Model is the application object, the View is its screen presentation, and the Controller defines the way the user interface reacts to user input. Before MVC, user interface designs tended to lump these objects together. MVC decouples them to increase flexibility and reuse.

MVC decouples views and models by establishing a subscribe/notify protocol between them. A view must ensure that its appearance reflects the state of the model. Whenever the model's data changes, the model notifies views that depend on it. In response, each view gets an opportunity to update itself. This approach lets you attach multiple views to a model to provide different presentations. You can also create new views for a model without rewriting it.

The following diagram shows a model and three views. (We've left out the controllers for simplicity.) The model contains some data values, and the views defining a spreadsheet, histogram, and pie chart display these data in various ways. The model communicates with its views when its values change, and the views communicate with the model to access these values.

Taken at face value, this example reflects a design that decouples views from models. But the design is applicable to a more general problem: decoupling objects so that changes to one can affect any number of others without requiring the changed object to know details of the others. This more general design is described by the Observer (page 293) design pattern.

Another feature of MVC is that views can be nested. For example, a control panel of buttons might be implemented as a complex view containing nested button views. The user interface for an object inspector can consist of nested views that may be reused in a debugger. MVC supports nested views with the CompositeView class, a subclass of View. CompositeView objects act just like View objects; a composite view can be used wherever a view can be used, but it also contains and manages nested views.

Again, we could think of this as a design that lets us treat a composite view just like we treat one of its components. But the design is applicable to a more general problem, which occurs whenever we want to group objects and treat the group like an individual object. This more general design is described by the Composite (163) design pattern. It lets you create a class hierarchy in which some subclasses define primitive objects (e.g., Button) and other classes define composite objects (CompositeView) that assemble the primitives into more complex objects.

MVC also lets you change the way a view responds to user input without changing its visual presentation. You might want to change the way it responds to the keyboard, for example, or have it use a pop-up menu instead of command keys. MVC encapsulates the response mechanism in a Controller object. There is a class hierarchy of controllers, making it easy to create a new controller as a variation on an existing one.

A view uses an instance of a Controller subclass to implement a particular response strategy; to implement a different strategy, simply replace the instance with a different kind of controller. It's even possible to change a view's controller at run-time to let the view change the way it responds to user input. For example, a view can be disabled so that it doesn't accept input simply by giving it a controller that ignores input events.

The View-Controller relationship is an example of the Strategy (315) design pattern. A Strategy is an object that represents an algorithm. It's useful when you want to replace the algorithm either statically or dynamically, when you have a lot of variants of the algorithm, or when the algorithm has complex data structures that you want to encapsulate.

MVC uses other design patterns, such as Factory Method (107) to specify the default controller class for a view and Decorator (175) to add scrolling to a view. But the main relationships in MVC are given by the Observer, Composite, and Strategy design patterns.

share|improve this answer
1  
It looks like this entire post minus the first two paragraphs is taken verbatim from Design Patterns. I've formatted that section as a quote so that readers understand that -- please edit if I've quoted paragraphs that are your own. –  William Shakespeare Mar 25 '13 at 14:05
1  
I have to disagree with your opinion that "the controller ends up spaghettied into the view." Perhaps it varies with the platform and framework that you're using, but it's far more common in Cocoa and Cocoa Touch programming to create appropriate controllers than to omit them. If an Objective-C programmer omits one of the categories, it's almost certain to be the model that suffers. –  William Shakespeare Mar 25 '13 at 14:11
    
If you agree that this is the "proper" interpretation of MVC then MVC buys absolutely nothing. It may as well just be MV and leave out the C because everytime you create a new View you also need to create a new Controller. So what's the point in taking pains to separate them other than for theoretical reasons of separation of concerns. –  Dunk Mar 28 '13 at 14:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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