views:

26605

answers:

15

When looking beyond the RAD (drag-drop and configure) way of building User Interfaces that many tools encourage you are likely to come across 2 design patterns called Model-View-Controller and Model-View-Presenter. My question has two parts to it:

  1. What issues do these patterns address?
  2. How are they similar?
  3. How are they different?
+2  A: 

Both of these frameworks aim to seperate concerns - for instance, interaction with a data source (model), application logic (or turning this data into useful information) (Controller/Presenter) and display code (View). In some cases the model can also be used to turn a data source into a higher level abstraction as well. A good example of this is the MVC Storefront project.

There is a discussion here regarding the differences between MVC vs MVP.

The distinction made is that in an MVC application traditionally has the view and the controller interact with the model, but not with each other.

MVP designs have the Presenter access the model and interact with the view.

Having said that, ASP.NET MVC is by these definitions an MVP framework because the Controller accesses the Model to populate the View which is meant to have no logic (just displays the variables provided by the Controller).

To perhaps get an idea of the ASP.NET MVC distinction from MVP, check out this MIX presentation by Scott Hanselman.

Graphain
+23  A: 

I blogged about this a while back, quoting on Todd Snyder's excellent post on the difference between the two.

Here are the key differences between the patterns:

MVP Pattern

  • View is more loosely coupled to the model. The presenter is responsible for binding the model to the view.
  • Easier to unit test because interaction with the view is through an interface
  • Usually view to presenter map one to one. Complex views may have multi presenters.

MVC Pattern

  • Controller are based on behaviors and can be shared across views
  • Can be responsible for determining which view to display

Best explanation on the web I could find.

Jon Limjap
updated link to Todd Synyder's post -> http://blogs.infragistics.com/blogs/todd_snyder/archive/2007/10/17/mvc-or-mvp-pattern-whats-the-difference.aspx
Eric Labashosky
+2  A: 
  • MVP = Model-View-Presenter
  • MVC = Model-View-Controller

    1. Both presentation patterns. They separate the dependencies between a Model (think Domain objects), your screen/web page (the View), and how your UI is supposed to behave (Presenter/Controller)
    2. They are fairly similar in concept, folks initialize the Presenter/Controller differently depending on taste.
    3. A great article on the differences is here. Most notable is that MVC pattern has the Model updating the View.
Brett Veenstra
+13  A: 

I recommend Phil Haack's blog entry about the ASP.NET MVC:

http://haacked.com/archive/2008/06/16/everything-you-wanted-to-know-about-mvc-and-mvp-but.aspx

And this post by Jeremy D. Miller:

http://codebetter.com/blogs/jeremy.miller/archive/2007/10/31/development-trivial-pursuit-the-difference-between-mvc-and-the-different-flavors-of-mvp.aspx

urini
So, the difference is a mere P? ;-)
Seiti
+10  A: 

MVP the View is in charge.
The View, in most cases, creates it's Presenter. The Presenter will interact with the model and manipulate the View through an interface. The View will sometimes interact with the Presenter, usually through some interface. This comes down to implementation, do you want the View to call methods on the presenter or do you want the View to have events the Presenter listens to. It boils down to this: The View knows about the Presenter. The View delegates to the Presenter.

MVC the Controller is in charge.
Controller is created or accessed based on some event/request, the controller then creates the appropriate View and interacts with the Model to further configure the View. It boils down to: Controller creates and manages View, View is slave to Controller. View does not know about Controller.

Brian Leahy
"View does not know about Controller." I think you mean that view has no contact directly with the model?
Lotus Notes
view should never know about the model in eiether one.
Brian Leahy
+5  A: 

Also worth remembering is that there are different types of MVP as well. Fowler have broken the pattern into two - Passive View and Supervising Controller.

When using Passive View your View typically implement a fain grained interface with properties mapping more or less directly to the underlaying UI widget. For instance you might have a ICustomerView with properties like Name and Address.

Your implementation might look something like this:

public class CustomerView : ICustomerView
{
    public string Name
    { 
        get { return txtName.Text; }
        set { txtName.Text = value; }
    }
}

Your Presenter class will talk to the model and "map" it to the view. This approach is called the "Passive View". The benefit is that the view is easy to test, and it is easier to move between UI platforms (Web/Win/XAML etc). The disadvantage is that you cant leverage things like databinding (which is really powerfull in frameworks like WPF and Silverlight).

The second flavor of MVP is the Supervising Controller. In that case your View might have a property called Customer, which then again is databound to the UI widgets. You don't have to think about synchronizing and micro-manage the view, and the Supervising Controller can step in and help when needed, for instance with compled interaction logic.

The third "flavor" of MVP (or someone would perhaps call it a separate pattern) is the Presentation Model (or sometimes referred to Model-View-ViewModel). Compared to the MVP you "merge" the M and the P into one class. You have your customer object which your UI widgets is data bound to, but you also have additional UI-spesific fields like "IsButtonEnabled", or "IsReadOnly" etc.

I think the best resource I've found to UI architecture is the series of blog posts done by Jeremy Miller over at http://codebetter.com/blogs/jeremy.miller/archive/2007/07/25/the-build-your-own-cab-series-table-of-contents.aspx. He covered all the flavors of MVP, and show C# code to implement them.

I have also blogged about the Model-View-ViewModel pattern in the context of Silverlight over at http://jonas.follesoe.no/YouCardRevisitedImplementingTheViewModelPattern.aspx.

Jonas Follesø
+14  A: 

MVP is not necessarily a scenario where the View is in charge (see Taligent's MVP for example). I find it unfortunate that people are still preaching this as a pattern as opposed to an anti-pattern (which it is in my books) as it contradicts "It's just a view" (Pragmatic Programmer). "It's just a view" states that the final view shown to the user is a secondary concern of the application. Microsoft's MVP pattern renders re-use of Views much more difficult and conveniently excuses Microsoft's designer from encouraging bad practice.

To be perfectly frank, I think the underlying concerns of MVC hold true for any MVP implementation and the differences are almost entirely semantic. As long as you are following separation of concerns between the view (that displays the data), the controller (that initialises and controls user interaction) and the model (the underlying data and/or services)) then you are acheiving the benefits of MVC. If you are acheiving the benefits then who really cares whether your pattern is MVC, MVP or Supervising Controller? The only real pattern remains as MVC, the rest are just differing flavours of it.

Consider this highly exciting article that comprehensively lists a number of these differing implementations. You may note that they're all basically doing the same thing but slightly differently.

I personally think MVP has only been recently re-introduced as a catchy term to either reduce arguments between semantic bigots who argue whether something is truly MVC or not or to justify Microsofts Rapid Application Development tools. Neither of these reasons in my books justify its existence as a separate design pattern.

Quibblesome
Thanks for the link to the Derek Greer article, that is an awesome read. +1 and a Nice Answer badge for that [after 1 1/2 years :-) ]
balpha
+259  A: 

Model-View-Presenter

In MVP, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed.

MVP tends to be a very natural pattern for achieving separated presentation in Web Forms. The reason is that the View is always created first by the ASP.NET runtime. You can find out more about both variants.

Two primary variations

Passive View: The View is as dumb as possible and contains almost zero logic. The Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead the View exposes setter properties which the Presenter uses to set the data. All state is managed in the Presenter and not the View.

  • Pro: maximum testability surface; clean separation of the View and Model
  • Con: more work (for example all the setter properties) as you are doing all the data binding yourself.

Supervising Controller: The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc.

  • Pro: by leveraging databinding the amount of code is reduced.
  • Con: there's less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.

Model-View-Controller

In the MVC, the Controller is responsible for determining which View is displayed in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application:

    Action in the View
        -> Call to Controller
        -> Controller Logic
        -> Controller returns the View.

One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders, and is completely stateless. In implementations of MVC the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary as if the View does not delegate to the Presenter, it will never get called.

Presentation Model

One other pattern to look at is the Presentation Model pattern. In this pattern there is no Presenter. Instead the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model, and may subscribe to events coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM completely encapsulates all of the behaviour for the view. This pattern is a very strong candidate for use in WPF applications and is also called Model-View-ViewModel.

There is a MSDN article about the Presentation Model and a section in the Composite Application Guidance for WPF (former Prism) about Separated Presentation Patterns

Glenn Block
Fantastic reply!
Slace
awesome!Two thumbs up!
Sung Meister
psst, use some formatting like bold text for chapters ;-). great explanation nonetheless!
VVS
Good job - very helpful!
itsmatt
Holy cow, this is the most lucid description i've ever come across. This could seriously replace about 3 books from my shelf!
Pierreten
Wow, that was a really really cool and useful response.
lidermin
Crystal clear and without a single diagram, the best pattern description ever.
Dmitry Ornatsky
Great description! 2 Typos: "The" twice in sentence 1, and "as" twice in first sentence under "passive view". Can't edit or I would.
Cory House
This is the most useful description I've seen of these patterns and the differences between them. 10 thumbs up!
Hans Løken
It is MVC which has a direct binding between Model and View, not MVP. Take a look at any serious design pattern directory, not what framework guys are talking about.Some links:http://msdn.microsoft.com/en-us/library/ff649643.aspxhttp://msdn.microsoft.com/en-us/magazine/cc188690.aspx
Zyx
Awesome explanation!
devoured elysium
+3  A: 

Both are patterns trying to separate presentation and business logic, decoupling business logic from UI aspects

Architecturally, MVP is Page Controller based approach where MVC is Front Controller based approach. That means that in MVP standard web form page life cycle is just enhanced by extracting the business logic from code behind. In other words, page is the one servicing http request. In other words, MVP IMHO is web form evolutionary type of enhancement. MVC on other hand changes completely the game because the request gets intercepted by controller class before page is loaded, the business logic is executed there and then at the end result of controller processing the data just dumped to the page ("view") In that sense, MVC looks (at least to me) a lot to Supervising Controller flavor of MVP enhanced with routing engine

Both of them enable TDD and have downsides and upsides.

Decision on how to choose one of them IMHO should be based on how much time one invested in ASP NET web form type of web development. If one would consider himself good in web forms, I would suggest MVP. If one would feel not so comfortable in things such as page life cycle etc MVC could be a way to go here.

Here's yet another blog post link giving a little bit more details on this topic

http://blog.vuscode.com/malovicn/archive/2007/12/18/model-view-presenter-mvp-vs-model-view-controller-mvc.aspx

Nikola Malovic
+1  A: 

I have used both MVP and MVC and although we as developers tend to focus on the technical differences of both patterns the point for MVP in IMHO is much more related to ease of adoption than anything else.

If I’m working in a team that already as a good background on web forms development style it’s far easier to introduce MVP than MVC. I would say that MVP in this scenario is a quick win.

My experience tells me that moving a team from web forms to MVP and then from MVP to MVC is relatively easy; moving from web forms to MVC is more difficult.

I leave here a link to a series of articles a friend of mine has published about MVP and MVC.

http://www.qsoft.be/post/Building-the-MVP-StoreFront-Gutthrie-style.aspx

Pedro Santos
+1  A: 

Something I don't get is why data binding has to reduce testability. I mean, a view is effectively based off of what could be thought of as one or more database views, right? There might be connections between rows in different views. Alternatively, we can talk object-oriented instead of relational, but that actually doesn't change anything -- we still have one or more distinct data entities.

If we view programming as data structures + algorithms, then wouldn't it be best to have the data structures made explicit as possible, and then develop algorithms that each depend on as small a piece of data as possible, with minimal coupling between the algorithms?

I sense very Java-esque FactoryFactoryFactory thought patterns here -- we want to have multiple views, multiple models, multiple degrees of freedom all over the place. It's almost like that is the driving force behind MVC and MVP and whatnot. Now let me ask this: how often is the cost you pay for this (and there most definitely is a cost) worth it?

I also see no discussion of how to efficiently manage state between HTTP requests. Haven't we learned from the functional folks (and the voluminous mistakes made by imperative spaghetti) that state is evil and should be minimized (and when used, should be well understood)?

I see a lot of usage of the terms MVC and MVP without much evidence that people think critically about them. Clearly, the problem is "them", me, or both...

+1  A: 

You may find the answers to Implementing MVC with Windows Forms helpful as they talk about the different options when implementing MVC and MVP

Ian Ringrose
+3  A: 

I wrote an article a few years ago on the topic of interactive application architecture patterns which includes a detailed discussion of both the MVC pattern and MVP pattern variants. You can find the article here.

Derek Greer
Funny, I searched MVP on SO just after reading your article. It is a great paper, with nice history background and good explanation of the (very) subtle differences in patterns.
PhiLho
+6  A: 

The best article on this topic is here - http://www.aspiringcraftsman.com/2007/08/interactive-application-architecture/

It covers all related patterns in depth and is a must read .

Unmesh Kondolikar