The SitePoint Forums have moved.

You can now find them here.
This forum is now closed to new posts, but you can browse existing content.
You can find out more information about the move and how to open a new account (if necessary) here.
If you get stuck you can get support by emailing forums@sitepoint.com

If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

RFC on MVC

I've been doing some major work on the Model View Controller pattern description on the WACT wiki. I think I've put everything that I wanted to say about MVC into it, but perhaps not with very clear or complete explanation. I could really use some feedback, comments or questions about areas that aren't clear. Thank you.

I haven't got much time right now, so I just did a quick review of the page. Alright, here goes

This is the value that your application delivers.

That is vague and ambiguous language and anybody can give his or her own interpretation to this.

Model is a mediator between view and controller?

I'd say Controller is a mediator between view and model rather. Although it's not a mediator in the GoF design pattern way, but in a loose way of speaking it is.

Because the controllers are so closely related to the view, they may also need to be partitioned with a parallel ?Composite hierarchy.

This is a topic that needs to be investigated more. I think that for many people, myself included, this is the part that we are having difficulties with to implement. Just take a look at the threads on this forum about “sub-views and –controllers” and “MVC-blocks”. I believe McGruff’s now legendary statement “Embed MVC in applications, not entire applications in MVC” also arose from this problem.

Changes to the model interface require parallel changes in the view and may require additional changes to the controller. certain code changes become more difficult.

It’s quite easy to debunk this argument, I think. When you for example add a new field to your database you have to make the same changes too: change your SQL code, alter your HTML forms, perhaps even add new pages to a site, etc. With MVC, having to make changes in more than one place may seem like a disadvantage, but that’s one of the things that comes with OOP: separation of concerns into separate classes. And I think separation of concerns can be regarded as a good thing.

The rest: man, thumbs up! I really like how you have managed to describe differences between various frameworks like Struts and other related patterns in a more formal way.

The separation into three concerns is inspired by a batch processing model where the controller represents program input, the model represents application processing and the view represents the output of the application.

I can't agree with this. Basically you say:

Code:

'MVC' 'BATCH'
controller == input
model == processing
view == output

I think MVC can't be compared to a 'processing' model because MVC doesn't describe a process.

The most important thing about MVC is that there's some kind of stateful model (either shared between application sessions or session specific) which can be manipulated by the user by some means of input (keyboard, mouse). This is done by the controller.

The view is only a representation of the model in a way that can be understood by the user (windows, widgets, text). The view just needs to stay in sync with the model .
There are several ways to do this:
- The controller can tell the view to update whenever it changes the model. (you cal this passive model)
- The model can tell it's registered observers it has changed. The observers decide if the view needs to be updated.

Maybe you can change it in a way I can understand, or just leave that part out... It only adds confusion.

Furthermore, I think that there's already good information on the web about MVC in general.

What's missing is in depth research at how MVC can be mapped to web-based applications consisting of javascript/html, URLs, http communcation, server side scripting and database back-end (and/or filesystem).

There's no simple one on one mapping for that. I've never seen any good research on that...

Lot's of people feel that MVC can't be really applied to the web, because the paradigms are too different. MVC has it's roots in object oriented GUI apps). The web is best explained as REST. (Representional State Transfer)

The controller receives and translates input to requests on the model or view.

If this is taken to mean that the MVC-controller handles http requests, we have one class with responsibility for the entire application. It has to interpret the request, decide which client page to serve up, decide if there are any pre or post client tasks to perform (which may or may not include other "print something" tasks such as emails, writing files etc).

That, to me, is screaming out to be refactored into separate components.

By embedding MVC routines, each MVC-controller receives a request from a workflow-management part of the app rather than interpreting an http request directly. Each controller manages its own model and view and nothing else. One MVC routine for client output, another for emails, etc. I tend to call these "PrintManagers" or "Printers"

Suddenly, the design comes back into focus. Really I'm still learning OOP design but that's my take on MVC.

That is vague and ambiguous language and anybody can give his or her own interpretation to this.

I agree. I'll work on a better description of the model and domain logic.

Originally Posted by Captain Proton

Model is a mediator between view and controller?

I'd say Controller is a mediator between view and model rather. Although it's not a mediator in the GoF design pattern way, but in a loose way of speaking it is.

What I was looking to say here was that the controller does not copy data values from the model to the view. It place them in the model and the view reads them from the model. So, the model acts as an intermediary between the controller and the view in this case. (as one might expect given the input-->processing-->view organization) This was really a note to myself to lookup the correct design pattern to express this, or to explain this better.

On the other hand, the controller can create, select and destroy the views without going through the model, so the division is not perfect. The organization of the pattern is a triangle, not a straight line.

Originally Posted by Captain Proton

Because the controllers are so closely related to the view, they may also need to be partitioned with a parallel ?Composite hierarchy.

This is a topic that needs to be investigated more. I think that for many people, myself included, this is the part that we are having difficulties with to implement. Just take a look at the threads on this forum about “sub-views and –controllers” and “MVC-blocks”. I believe McGruff’s now legendary statement “Embed MVC in applications, not entire applications in MVC” also arose from this problem.

I agree. I think its obvious that its good to decompose each of the concerns of the MVC triad. The view is easy to decompose simply by dividing up the visual area of the output in a hierarchy of rectangles.

Do the view and model have to have parallel decomposition? A naked objects approach would seem to say yes. My experience with this has been bad, though, so I am tentatively working off the hypothesis that there must be a degree of freedom between the organization of the model and the views. (a task model driven user interface design versus a data model driven user interface design).

So do the controllers require a parallel decomposition to the view? There is in the GUI MVC. The view hierarchy defines a hierarchy which the controllers can use to determine which controller should react to the user input. Is this true in web MVC? this is a question which has come up in designing WACT controller components. I don't have a good answer for this yet. Based on my experience with models, I want to say no, that a degree of freedom would be useful. The jury is still out. I think I need to write some code to answer this question for myself.

Originally Posted by Captain Proton

Changes to the model interface require parallel changes in the view and may require additional changes to the controller. certain code changes become more difficult.

It’s quite easy to debunk this argument, I think. When you for example add a new field to your database you have to make the same changes too: change your SQL code, alter your HTML forms, perhaps even add new pages to a site, etc. With MVC, having to make changes in more than one place may seem like a disadvantage, but that’s one of the things that comes with OOP: separation of concerns into separate classes. And I think separation of concerns can be regarded as a good thing.

I don't think there is any question that some changes require parallel changes in MVC and that changing something in multiple places is more difficult than changing it in one place. (you essentially say the same thing.) Whether this is worth it or not is a separate question, handled elsewhere in the document

Originally Posted by Captain Proton

The rest: man, thumbs up! I really like how you have managed to describe differences between various frameworks like Struts and other related patterns in a more formal way.

Thanks. I have learned and continue to learn a lot by writing it. I hope it turns out to be useful to other people.

Do the view and model have to have parallel decomposition? ... do the controllers require a parallel decomposition to the view?

I'd say yes for views and models. It's almost certain that certain page blocks will be re-used on different pages (header eg) so it makes sense to separate models & views for each page block.

However, a single controller could happily manage a list of sub-models & corresponding views - at least I haven't encountered any problems with that approach so far. A separate controller for each block may not be necessary, and presumably would still require some kind of manager object on top anyway?

A single controller could receive a list of block meta data, load all the models and then print each in the appropriate view (and in the correct order).

Models need to talk to each other - eg a HeadHtml object (everything between the < head > tags) might want to gather a page title, custom CSS styles or some keywords from other sub-models. The way I've been doing that is to load all the sub-models in a pipe: each can observe the others, and the "controller" also observes the pipe, gathering the page vars output from each sub-model.

I tend to call the latter Printers or PrintManagers rather than a controller. They can present a simple interface:

The controller receives and translates input to requests on the model or view.

If this is taken to mean that the MVC-controller handles http requests, we have one class with responsibility for the entire application. It has to interpret the request, decide which client page to serve up, decide if there are any pre or post client tasks to perform (which may or may not include other "print something" tasks such as emails, writing files etc).

Back in the late 80s when I was writing Macintosh GUI programs, those programs had a single point where the application received input from the operating system, called an event loop. I think windows copied this convention with their event queue. Writing applications was Tedious with a capital T. Hello World (well skeleton) was hundreds of lines.

I think web applications are at this stage today. They are written to receive their input from the web server at a single point. (I know thats not strictly true, go with me on this one.)

Originally Posted by McGruff

That, to me, is screaming out to be refactored into separate components.

Then in the early/mid nineties, frameworks like MacApp, MFC and environments like visual basic and Delphi took the event loop away from the programmer and put it into the framework. Now, the programmer built their applications out of components and productivity dramatically increased for GUI apps.

However, the event loop was still there, buried inside the framework, which used the visual hierarchy of components that the programmer created to dispatch relevant input to the proper component. Each component handled both the input and the output. There was no point in separating them.

Perhaps we are now seeing a parallel with web frameworks. Will they improve productivity as much? One thing, they don't have is a convenient visual hierarchy upon which to base a controller decomposition. So how do they do it?

I added action chains to WACT, BTW and found them to be a big improvement over the single action style.

I don't think this way of decomposing the controllers is well thought out yet. struts (and other similiar frameworks) for example has special types of actions like DispatchAction and RelayAction. Some of this I think is due to the constraint having a single front controller. These special actions are like little front controllers.

One thing that I've been experimenting with is creating a hierarchy of front controllers. My hope is to improve the decomposition of the controller part of the MVC.

There is more decomposition and refactoring to be done here.

Originally Posted by McGruff

By embedding MVC routines, each MVC-controller receives a request from a workflow-management part of the app rather than interpreting an http request directly. Each controller manages its own model and view and nothing else. One MVC routine for client output, another for emails, etc. I tend to call these "PrintManagers" or "Printers"

sounds like you have a controller decomposition that works for you, although I don't necessarily understand it from your description.

Originally Posted by McGruff

Suddenly, the design comes back into focus. Really I'm still learning OOP design but that's my take on MVC.

I tried to mention that on the wiki page. MVC is much easier to understand at low levels of granularity than at the higher.

sounds like you have a controller decomposition that works for you, although I don't necessarily understand it from your description

An HttpRequestManager would decide which tasks to perform in response to a request - pre/post client as well as client output.

Client output would be created with a ClientPagePrinter. Maybe there are also some emails to send after the client output: an EmailPrinter would be used.

Anything which prints some form of human readable output - client page, files, emails - has its own Printer class. Instances of these classes encapsulate separate MVC routines within the app.

All printers have an interface:

loadModels
loadViews
printPage

I think Printers (ie controllers) shouldn't get involved with interpreting the http request. They just print what they're told to by whatever is managing the workflow ie a ClientPagePrinter is given a list of models and views, an EmailPrinter a list of addresses and a message model, etc.

Well, I have had the fortune to work on two large systems that do the same thing, but were independently developed using two different approaches. I worked for several years on both systems, but was not involved in the initial design of either.

I'll call one approach data model driven user interface development. The naked objects approach. This system was designed by developers with an oracle database background. They designed the data model and developed a user interface that paralleled that model. It worked very well for the developers, but the user community complained that the system was too difficult to use. A good example of this was when a user went to add a part to the system, there were over 20 tables that need to be touched, and because the UI paralleled the model structure, that meant 20+ views to visit for this one task.

I'll call the other approach user interface driven model development. The Software For Use approach. This system was designed by the CEO (Phd in physics, not a programmer) of the company running it as he built the company from a handful of employees to several hundred. The user interface for this system was designed so that the person doing a task had everything needed at hand. The backend data storage was defined to reflect this and it was a mess. The users liked this system, but the programmers complained about it.

So, based on this experience, I think any approach where the model and view mirror each other too closely is bad. There has to be a method for allowing an extra degree of freedom between the two.

A little mapping between the software for use approach and MVC (read the papers on the site):
WorkSpace = compound view / composite view
Tool = View element that triggers an action in the controller
Material = View element that mirrors the model.

Originally Posted by McGruff

It's almost certain that certain page blocks will be re-used on different pages (header eg) so it makes sense to separate models & views for each page block.

There doesn't have to be a 1:1 correspondence between model and view. The same model information might appear in different blocks.

Originally Posted by McGruff

Models need to talk to each other - eg a HeadHtml object (everything between the < head > tags) might want to gather a page title, custom CSS styles or some keywords from other sub-models.

This doesn't really sound like a domain model to me. I think this is an area where there is alot of confusion in MVC.

To me, MVC is about separating the domain logic from the user interface where the domain logic is represented by the model, and the user interface is represented by the view and controller.

Yet, there are some "model like" things that are definitely NOT domain oriented and thus cannot go into the model side of this division. I tried to talk about this a bit in the section on User Interface Models, but this is not an area which I've explored enough to say anything well.

This idea is sometimes called an ApplicationModel or model model view controller. The idea being there are two models, one for the domain stuff and one for user interface stuff.

I've been looking at MVC implementations and frameworks for a long time. Largely these investigations have been the pros/cons of the front controller, but they have since been all over the map.

When you're talking about MVC theory, it seems like the debate can never end (we'll see how many replies we get on this thread) At the core of it, the model, view, and controller make a great pattern, but the implementation varies from project to project. Web projects are different from desktop GUIs, are different from web services and applying MVC on any of those tasks can vary greatly.

I've used Ismo before, and have since picked up Mojavi as the best framework that gets MVC 'right' without forcing your application "into" their framework too much. The biggest gotchas I've seen in any MVC framework are:

- Applying aggregate functions (like security, authorization, etc).
- "regional" data.: you can have global data (like a style sheet), but there are things that might cross models, or cross views. Actionchains are a pretty good solution, but I have an eery(sp?) feeling that there might be cases where you want to create a chain execute various actions along the way in slightly different manners to customize the output.

Ok, that ends my rant on general MVC, I have some comments on your write up:

- Frontcontroller versus ApplicationController will be the same implementation for the majority of people. I could see a frontcontroller that dispatches to various applications, but most people have 1 front for 1 app. A front controller is probably easily added to a front+page controller if it only dispatches to applications.

In fact, if you look at MVC frameworks, a front controller is like a higher level MVC framework that instead of dispatching to actions, dispatches to applications (who probably in turn dispatch to their own specific actions).

Your comment on applying design patterns is true for any project. If you want MVC and you have 'god objects', you'll end up with big balls of mud even if you didn't use MVC.

One final comment for now on pros/cons of adopting MVC.
My biggest pro has to be the organization it gives you. When you pick up something like Mojavi you can easily address all URLs, and it forces you to put things in certain places or it just won't work. This way it is very easy to tell what's going on and build an application.

The biggest con of an MVC framework has to be the performance hit and the tendency to write your application as part of the framework. This was my beef with Ismo because it required you to extend a bunch of its classes in your application.

There doesn't have to be a 1:1 correspondence between model and view. The same model information might appear in different blocks.

Yes. I maybe didn't say exactly but each block-model can be printed in any number of different block-views.

Originally Posted by Selkirk

This doesn't really sound like a domain model to me. I think this is an area where there is alot of confusion in MVC.

There could well be... My "block-models" gather data, process the data, share some of that data if need be, and basically exist to create a bunch of page vars which are echo'd out in each block-view. That may not be a complete domain model but it's all the Printer class I described needs to know about.

Anyway, I'm possibly talking about my own work too much now. Thanks for all the effort put into the Wiki

With MVC it can be easier to test the core of the application, as encapsulated by the model.

The corollary to this is "It is damn hard to write tests for views or actions(controllers)."

What I have found in writing tests for Phrame based applications was that the only thing that was approachable from a unit testing standpoint was the Model classes, which were all my code, rather than mixed in with the framework.

The original Smalltalk-80 paper on MVC doesn't cut it in terms of describing how MVC fits into the Web. All of the Web implementations that I have researched are merely subjective "interpretations" of the *right* way to structure an application using MVC. I think that MVC is about separation. How this separation is achieved is left up to the developer.

I have gained valuable insight into how the MVC pattern can be applied to Web-based software applications from:

Core J2EE Patterns
Patterns of Enterprise Application Architecture

I highly recommend both books (even if you don't program in Java). Struts is an example of a mature framework that implements the MVC pattern, however, it relies heavily on the language of implementation (e.g. Java Servlets are resident in memory between requests). There are some interesting things going on over at Microsoft. They have an example that uses the Observer pattern to implement MVC.

On further reflection, I think the idea I've been propagating about "embedding MVC" isn't correct.

The Printers which I outlined above are, I think, just views. Each printer/view is supplied with a list of objects with which to query the model and a list of whatever templates are required to present the data. They don't encapsulate MVC - just V.

Selkirk: Nice explanation of MVC you wrote there. But there are some minor points I'd like to see added to the cons of MVC:

Originally Posted by WACT

Model View Controller (MVC) is a time tested method of separating the user interface of an application from its DomainLogic.

That's certainly true, but IMO web applications don't have user interfaces: they're the lowest layer of a three tier system (client application - webserver - web application). Using MVC to describe a web application forces people to envision their application as if it's directly linked to the user, which leads to a big misunderstanding of web applications. So I don't really see the relevance of the 'time tested' part of your sentence. Experience has shown that wings work really well on airplanes. That doesn't mean we should stick them on submarines as well....

Originally Posted by seratonin

I think that MVC is about separation. How this separation is achieved is left up to the developer.

The problem is that many people now seem to believe that MVC is the only way to achieve 'separation', and that separation of presentation and business logic is the only issue we need to solve. Both of these ideas are simply wrong.

- - -

I'm not opposed to people trying to gain a better understanding of MVC; I think the pattern can work quite well within its original context. But I strongly oppose the current tendency to use MVC as an architecture for web applications, as well as the vocabulary to discuss the web application problem domain. It was never intended for either of these, and IMO history has shown that using MVC as it is being used now doesn't solve any of the problems that really need to be solved. Even worse, it only creates problems that shouldn't even exist.

The problem is that many people now seem to believe that MVC is the only way to achieve 'separation', and that separation of presentation and business logic is the only issue we need to solve. Both of these ideas are simply wrong.

- - -

I'm not opposed to people trying to gain a better understanding of MVC; I think the pattern can work quite well within its original context. But I strongly oppose the current tendency to use MVC as an architecture for web applications, as well as the vocabulary to discuss the web application problem domain. It was never intended for either of these, and IMO history has shown that using MVC as it is being used now doesn't solve any of the problems that really need to be solved. Even worse, it only creates problems that shouldn't even exist.

I agree. MVC isn't the only way to achieve separation. I do think, however, that MVC can be used quite effectively to create Web-based software applications. I look at the Web browser as the User Interface. The user makes gestures (clicks) on the interface which are translated into HTTP requests (GET/POST). These requests are handled on the server by the Web application. The Web application processes them and generates a response. Fundamentally, how is that much different from a desktop application where a user clicks a button and the application does something in response? Sure there is a time lag and the "interface" is really just a set of textual "instructions" or markup for the Web browser to display the next screen, but I don't think it is too far off. The main difference that I see is the stateless nature of the request/response model. There are, however, several ways of getting around this (e.g. cookies, url re-writing, hidden form fields, etc.). Even though MVC was originally meant for desktop GUI applications and Web applications have their own unique set of problems (stateless nature, validation, authentication, authorization, etc.), I think that a Web-based software application can still benefit from the MVC architecture.

The biggest gotchas I've seen in any MVC framework are:
- Applying aggregate functions (like security, authorization, etc).
- "regional" data.: you can have global data (like a style sheet), but there are things that might cross models, or cross views. Actionchains are a pretty good solution, but I have an eery(sp?) feeling that there might be cases where you want to create a chain execute various actions along the way in slightly different manners to customize the output.

These types of things are covered under the idea of CentralizedRequestLogic. These are basically code duplication elimination mechanisms. Along with inheritance.

The problem with many MVC frameworks is that they reserve some of the best structuring mechanisms for themselves.

A good example is an MVC framework that requires you to inherit from specific objects, such as for command objects. This robs you of the ability to create your own inheritance hierarchy. (WACT will never have a parent class for actions for this reason.)

Another example is having a heavyweight front controller robs you of the ability to centralize your own logic in the front controller. The work around to this is for the framework to provide an intercepting filter capability. (WACT defines a lightwieght front controller interface. Instead of a single framework mandated implementation, I want to encourage many front controller implementations, and encourage the application programmers to subclass these standard implementations or make writing replacements easy.)

Another problem is that these frameworks only let you have a single front controller. I see alot of front controller like code get added to actions in MVC frameworks because of this. Again, intercepting filters mitigate this somewhat. I'd like WACT to have a hierarchical front controller capability.

Originally Posted by NativeMind

- Frontcontroller versus ApplicationController will be the same implementation for the majority of people.