78

It seems everyone doing web applications nowadays wants to use MVC for everything. I find it hard to convince myself to use this pattern, however. I understand the general idea is to separate the backend logic from the frontend that represents the program. Generally, it seems that the views always depend on the controller to some extent, which ends up depending on the model. I don't see what advantage adding the controller gets me. I've read a lot of hype about "this is the way applications should be designed", but maybe I still don't understand what is supposed to go where. Whenever I talk to others about MVC it seems everyone has a different idea of what belongs in what category.

So, why should I use MVC? What do I gain by using MVC over just separating the frontend from the backend logic? (Most "advantages" I see of this pattern are gained just by separating interface from implementation, and fail to explain the purpose of having a separate "controller")

Billy ONeal
  • 8,073
  • 6
  • 43
  • 57
  • 9
    MVC is simply a implementation of [Seperation of Concerns](http://en.wikipedia.org/wiki/Separation_of_concerns). Any implementation will do. Not using Seperations of Concerns tends to lead towards [a Big ball of mud](http://en.wikipedia.org/wiki/Big_ball_of_mud) – Raynos Sep 01 '11 at 23:43
  • 1
    @Raynos: Perhaps. But that's not where the "hype" is going. – Billy ONeal Sep 01 '11 at 23:44
  • 3
    hype obeys [the hype curve](http://en.wikipedia.org/wiki/Hype_cycle). Don't let it influence you too much. From my point of view, MVC is a solid architecture for SoC and easy to implement. I can't think of a solid alternative. – Raynos Sep 01 '11 at 23:49
  • most existing user-interface frameworks tightly link V and C and when you switch to another you'll need to rewrite both the view and controller (the interface from M to the what the user sees) – ratchet freak Sep 02 '11 at 01:16
  • But Separation of Concerns is a property of OO development. You don't have to use a MVW pattern to implement a correct Separation of Concerns code? – Bastien Vandamme Apr 16 '14 at 18:07

7 Answers7

52

Heh. Martin Fowler agrees with your confusion about MVC:

I don't find it terribly useful to think of MVC as a pattern because it contains quite a few different ideas. Different people reading about MVC in different places take different ideas from it and describe these as 'MVC'. If this doesn't cause enough confusion you then get the effect of misunderstandings of MVC that develop through a system of Chinese whispers.

However, he goes on to give one of the more cogent explanations of what motivates MVC:

At the heart of MVC is what I call Separated Presentation. The idea behind Separated Presentation is to make a clear division between domain objects that model our perception of the real world, and presentation objects that are the GUI elements we see on the screen. Domain objects should be completely self contained and work without reference to the presentation, they should also be able to support multiple presentations, possibly simultaneously.

You can read Fowler's entire article here.

Gnawme
  • 1,333
  • 8
  • 7
20

I feel this depends much upon the problem you are tackling. I see the separation as follows:

Model - how do we represent the data? For example, how do I go from my objects to a persistent storage such as a DB -> how do I save my 'User' object to the database?

Controller - what am I doing? This is the action that's taking place, and what, on a conceptual level, needs to be carried out. For example, what stages do I need to go through to invoice a User? N.B. this may affect any amount of objects, but does not know anything about how they are persisted to the DB.

View - how do I render the result?

The problem I feel you are seeing is that a lot of web applications are a glorified CRUD (Create-Retrieve-Update-Delete) interface to a DB. i.e. the controller is told to 'add a user', and it then simply tells the model to 'add a user'. Nothing is gained.

However, in projects where the actions you carry out do not apply directly to changes in the model a controller makes life much easier and the system more maintainable.

Unk
  • 301
  • 1
  • 3
  • 1
    "in projects where the actions you carry out do not apply directly to changes in the model" What do you mean by "model" here? The database? Because everyone I've talked to says that such actions still belong in a model, not in controllers. (e.g. that controllers should only be dealing with HTTP stuff...) – Billy ONeal Sep 01 '11 at 19:10
  • What counts as HTTP stuff? I would include the following in a controller: Unmarshalling HTTP request parameters, checking the parameters for basic sanity, determining what needs to be done, visiting appropriate model objects (to read, write or both), producing a final result based upon the model's responses, passing that off to the view. A silly example of something _only_ a controller would be used for might be a web service generating a random number - in this case there is no 'model' to look at (in my mind at least...) – Unk Sep 01 '11 at 19:26
  • Those are all model concerns. Even "deciding what needs to be done" (the "front controller") is a model. – Billy ONeal Sep 01 '11 at 22:07
  • My feeling (possibly unusual) is that we shouldn't just lump all 'domain logic' under a single 'model' concept. Domain logic can contain behaviours as well as entities - not always intrinsically linked. In a larger system carrying out complex actions, I'd say there's always easily more than 3 layers. e.g. Raw storage -> entities -> behaviour -> mapping of requests/responses to behaviour inputs/outputs -> presentation. As long as your behaviour is completely separated from _both_ your underlying data storage and your presentation layer, I'm happy. – Unk Sep 01 '11 at 22:40
  • 2
    Not to mention controllers are useful for not hard-coupling your models to your views. As well as allowing you to connect many views to many models through one controller. – Raynos Sep 01 '11 at 23:53
  • @Raynos: I don't understand. The model shouldn't be concerned with what's going on in a view; and the view should be allowed to mess with whatever model it so desires. If the view had no connection with the model at all, the controllers become huge, and you lose most any benefit you might gain from the looser coupling. – Billy ONeal Sep 02 '11 at 01:46
  • @Raynos: in mvc every user-facing form/report is implemented a model-view-controller triad. I would think that orchestrating multiple view/models should be done by a "super"controller controlling the controllers of those mvc-triads. – Marjan Venema Sep 02 '11 at 06:09
  • 1
    @Billy: if you allow a view to "mess" with the model - other than quering it for its values - you end up with views that are more like controllers. I think more in terms of the Model-GUI-Mediator incarnation of MVC. The controller mediates between the Model (behaviour and data of the domain) and GUI (on-screen representation of the model). The view just passes interactions to the controller (user clicked ...). The controller decides what (if any) needs to be called on the model. Benefits: ... – Marjan Venema Sep 02 '11 at 06:20
  • @Billy: ...Benefits: You can swap out view and model implementations independently. The behaviour of the app (the user interface) can automatically be tested through testing the controllers. The views are as thin as possible and "merely" serve as a conduit between the controller and whatever visual library you use. – Marjan Venema Sep 02 '11 at 06:20
  • @Marjan: You get all of those benefits by separating the presentation and business-logic layers. That doesn't explain the benefit of MVC specifically. – Billy ONeal Sep 07 '11 at 17:14
  • @Billy: MVC is a pattern to separate the presentation and business logic layers. So their benefits are at least similar and are most probably equal. Having the separate controller allows you to do the design in your favourite IDE using all RAD features you like, while helping you to keep behavioural logic out of the "code behind form" kind of event handlers. Which is what uncontrolled RAD development tends to lead to... – Marjan Venema Sep 07 '11 at 20:00
8

You shouldn't.

Let me rephrase that. You should use an architecture that separates logic from your views. If needed, you should use an architecture that utilizes a controller (such as MVC) if there is logic required that doesn't necessarily fit into a model (such as, say, a tree traversal parsing URL chunks).

Coming from CI and Yii, I thought that having a dedicated controller was a really cool idea. However, when developing applications with proper RESTful interfaces, then the need for a controller to handle non-model-specific logic seems to lessen. Thus, when moving to Django and then Pyramid (neither of which follow the MVC architecture completely), I found that the controller was not actually a required component for the applications I was building. Note that both frameworks have "controller'ish" features, such as URL Dispatching in Pyramid, but it's a configuration thing, not a runtime thing (such as CController in Yii).

At the end of the day, what's really important is the separation of view from logic. Not only does this clean things up in terms of implementation, but it also allows FE/BE engineers to work in parallel (when working in a team environment).

(Side note: I don't develop web apps professionally, so there may be something that I'm missing)

Demian Brecht
  • 17,555
  • 1
  • 47
  • 81
  • I totally agree, good answer. The controller isn't always necessary, it's just meant as a strategy for the view to communicate with the model. – Falcon Sep 01 '11 at 19:17
  • @Falcon: See, that's my confusion. I've seen more than one person say that the view shouldn't talk with the controller at all; that it should talk only to the model... – Billy ONeal Sep 01 '11 at 23:43
  • 1
    If you're using an actual MVC implementation, the view *doesn't* talk to the controller (or the model for that matter). The controller sets the model's state, prepares the data for the view and pushes it to the view. – Demian Brecht Sep 01 '11 at 23:44
  • @Demian: I've heard the reverse (that controllers should do effectively nothing). Often. That's my biggest problem with this pattern; nobody seems to agree on what it is. – Billy ONeal Sep 02 '11 at 15:07
  • 3
    Yep, I've often heard that if you get 10 programmers in a room, you'll get 9 different definition of what MVC is. Really, the main point is the separation of concerns. What else goes on seems to be a religious debate. – Demian Brecht Sep 02 '11 at 15:14
2

Yes, the terminology on this is a mess. It's hard to talk about because you never quite what somebody means by the terms.

As far as why a separate controller, the reason might depend on which version of controller you are talk about.

You might want a controller because when you run tests the view has a bunch of widgets that you didn't write and probably don't want to test. Yes, you separated implementation from inheritance, so you can use a stub or mock to test other stuff, but when you test your concrete view itself it's harder. If you had a controller that didn't have any widgets running that same code then you could test that directly, and maybe not need to test the widgets via script.

The other versions are IMHO harder to show a concrete benefit for. I think it's mostly a separation of concerns issue - separate pure visual GUI concerns from logic that applies to the GUI but isn't part of the business model (things like, translate updates from the model into which widgets should be visible). But in practice the two classes are likely to be so tightly coupled (even if they communicate through interfaces) that it's hard to be overly upset at merging them into just a view, and just keep an eye out for ways the functionality might be more reusable if they were split.

psr
  • 12,846
  • 5
  • 39
  • 67
0

Simply put: separation of concerns. Aside from all the talk about the "correct" way of doing things, having cleaner code, etc. you can just say that MVC allows you to more easily reuse your code. Basicaly you program your models and your controllers and you can use them indistinctly in a web app, a desk app, a service, anywhere without much effort.

AJC
  • 1,439
  • 2
  • 10
  • 15
  • 2
    That's no different than simply defining a UI layer and a functional layer. You haven't explained why the controller bit is necessary. – Billy ONeal Sep 01 '11 at 22:07
-3

Well the basic reason for using an MVC structure shows up in an industry setup, where a single work process, a single model is followed for the development of any application. So, in case, if the project moves on from one module of an organization to another, it is much easier to provide a better understanding of the work scenario. It incorporates clarity of work.
While you, as an individual would have a different approach for your application, you when working in a combined fashion with an associate, would first discuss and land upon a commonly agreed model by the two (you and your associate). And in such a case, it separates the responsibilities assigned to you and your associate respectively with a distinctive margin.

ikartik90
  • 105
  • 4
-3

I think MVC is used just a buzzword by theorists that are managers. However, having said that, the current iteration of the web with HTML5 prevalent, responsive design, and trying to create a single line of database programming that will work on the web and on an iPhone lends itself to the general ideas of MVC. The web front-end technology is literally moving at the speed of light right now with Jquery, new iterations of CSS control, whereas the server side of things is moving at the pace of a snail.

Eventually, everything on the server will really just be services or "applets" that pump data to the front-end and depending on what kind of client you have, that data will be consumed and displayed differently. In that sense, MVC makes sense.

In this regard, I believe in the current real world, the MVVM is really a better "pattern" or whatever you want to call it than a controller because a controller always has to go back to the model to change the view and this is slow. In the MVVM pattern the ViewModel can give immediate updates to the view. In addition the MVVM model promotes RESTful design principals IMHO.

  • is this merely your opinion, or you can back it up somehow? – gnat May 08 '15 at 19:21
  • 3
    ( did not downvote) Well, it's been a buzzword going on 40+ years now if it is. – Billy ONeal May 08 '15 at 19:29
  • 2
    I would encourage you to put some additional research into the origins of the MVC pattern and the additional patterns that it spawned such as MVP and MVVM. There's a lot more history to the pattern than the current buzzwordiness would lead you to believe. –  May 08 '15 at 19:29
  • 1
    From [Model View Controller History](http://c2.com/cgi/wiki?ModelViewControllerHistory): "MVC was invented at Xerox Parc in the 70's, apparently by Trygve Reenskaug. I believe its first public appearance was in Smalltalk-80. For a long time there was virtually no public information about MVC, even in Smalltalk-80 documentation. The first significant paper published on MVC was "A Cookbook for Using the Model-View-Controller User Interface Paradigm in Smalltalk -80", by Glenn Krasner and Stephen Pope, published in the August/September 1988 issue of the JournalOfObjectOrientedProgramming (JOOP)." –  May 08 '15 at 19:38
  • There are lots of much more important buzzwords like KISS that have been around for longer and get a whole lot LESS attention. – Michael Barber May 15 '15 at 14:55