in

Nikola Malovic

.NET development and architecture
VusCode - Coding dreams since 1998

Add to Google Reader or Homepage Add to Pageflakes Subscribe in NewsGator Online Subscribe in Bloglines Add to Technorati Favorites View Nikola Malovic's profile on LinkedIn

VusCode - Coding dreams since 1998!

.NET exploration, articles, cool links, surf logs, book reviews, .net, c#, smart clients, software factories, patterns & practices, web casts and much more

Model View Presenter (MVP) pattern

Update: The focus of this article is to describe the wiring between the presenter and view which are IMHO the most important thing to get for MVP pattern.
I deliberately melt down presenter and model (by having the presenter itself retrieving the user data in SetUpResultData method instead to call the separate UserRepository component) to avoid having additional service interface into the constructor pattern and making whole L100 example more complex. This is not OK outside of this example context and you shouldn't do it.
I have one more example explaining in more depth MVP pattern which you should read after this article which has more precise description

Introduction

MVP pattern is a type of UI design pattern which enables decoupling of the UI logic without UI representation and by that enables treating code base without consideration on presentation technology used.

One of the commonly stated advantages of this approach is that it enables writing of appropriate test scripts to test UI part of application. MVP enables that without the need of using third party tools which scripts user UI actions and which are fairly easy to use for testing simple actions like button click, but to write a user UI scripts for data manipulation of a grid or some more complex layout. All the logic is inside the presenter and the presenter is talking to view only through the interface, so any mock object could be used for testing as long it implements the view interface

Second advantage is the fact that by decoupling code in presenter level we are enabling reuse of the code logic to totally different presentation technologies. For the example, the same presenter can be used without any problem in both Web Form and Win Form worlds, as long as they implement agreed interface

Third advantage is in the fact that in big companies (like the one I'm working in) to implement your supportive UI code, you are often forced to wait on UX (user experience) people to make the web forms and that sometimes is a very long period. Also the way of communication between products, tech leads and developers is quite often based on some word document based FRD which (from developer perspective) is not the most precise way of specifying requirements. MVP is allowing the tech leads to crystallize results of an FRD to a set of interface definition of a view and that interface could be immediate base for developers to start coding , without waiting for anyone knowing very precise what are the requirements. (Who said TDD? :) )

Illustration 1. Logical view of the MVP pattern.

 

Short diagram description

View is responsible for visual representation of the form and it contains a presenter in private field. View is implementing interface whose members are approximated and technology striped UI elements of the view. When some event occurs on view is just forwarding it to presenter and it is presenter responsibility to handle the event. Presenter is manipulating view by talking to interface representation of the view. Presenter should never reference directly view members (UI controls). Presenter for his logic operations is using Model which can be persisted state or representation of the object which provides necessary functionality

Implementation procedure:

Create a view by using standard Visual Studio IDE tools.

For my example I will create first a web form with:

    • a label on top which would show possible validation error
    • Last name, first name, address and a city text boxes
    • Search text box with a button

Illustration 2. UI look of the view made by web form

Interface would be created in a separate project called presenter so we could reuse it later to demonstrate usage outside of our web application. Web application should have a reference to the presenter project

Illustration 3. Project structure  - separating and referencing presenter

Create a interface as an abstract form of a view with setters only for text boxes (because presenter would fill == set them) and getter property only for searcher (presenter would take that value and perform a search)

Illustration 4. View interface definition

namespace Presenter

{

    public interface IUserView

    {

        string FirstName { set;}

        string LastName { set;}

        string Address { set;}

        string City { set;}

        string ErrorMessage { set;}

        string SearchCriteria { get;}

    }

}

After creation of interface we are implementing it on view by setting and getting UI element values in the property

Illustration 5. View interface implementation

    #region IUserView Members

    public string FirstName

    {

        set { firstName.Text = value; }

    }

    public string LastName

    {

        set { lastName.Text = value; }

    }

    public string Address

    {

        set { address.Text = value; }

    }

    public string City

    {

        set { city.Text = value; }

    }

    public string ErrorMessage

    {

        set

        {

            errorMessageLabel.Text = value;

            errorMessageLabel.Visible = value != "";

        }

    }

    public string SearchCriteria

    {

        get { return searchCriteria.Text; }

    }

    #endregion


Creation of presenter class includes creation of a private field of view interface type and overloading of a constructor to accept that view interface

Illustration 6. Presenter  wiring the view

 
namespace Presenter

{

    public class UserViewPresenter

    {

        IUserView _view;

        /// <summary>

        /// Initializes a new instance of the UserViewPresenter class.

        /// </summary>

        /// <param name="view"></param>

        public UserViewPresenter(IUserView view)

        {

            _view = view;

            SetCustomerData();

        }

Presenter would have to implement business logic, which In our example is finding of a customer for a given code. I’ve created Customer.xml file as D:\Customer.XML

Illustration 7. Exampled data used for sample 


Presenter would implement therefore a method named SetCustomerData which task is to find a customer of a given code and update the view with resulting data. In case the entered code is not a valid number presenter would show appropriate message on validator that there is a syntax error. In case there are no contacts with a given code presenter should empty view and show a message that not existing code has been entered.

Illustration 8. Implementation of a presenter logic 

public void SetCustomerData()

{

int searchCode;

      bool isValid = int.TryParse

            (_view.SearchCriteria, out searchCode);

if (isValid)

      {

            using (DataSet ds = new DataSet())

            {

                  string filePath=string.Format(

"{0}Customers.xml",

AppDomain.CurrentDomain.BaseDirectory                   

                  );

ds.ReadXml(filePath);

                  ds.Tables[0].PrimaryKey

                        = new DataColumn[]

{ds.Tables[0].Columns["Code"]};

                        DataRow dr=

                            ds.Tables[0].Rows.Find

                            (_view.SearchCriteria);

if (dr != null)

                  {

                        _view.FirstName

                           = dr["FirstName"].ToString();

                        _view.LastName

                           = dr["LastName"].ToString();

                        _view.Address

                           = dr["Address"].ToString();

                        _view.City

                           = dr["City"].ToString();

                        _view.ErrorMessage

                           = "";

}

                  else

                  {

                        _view.FirstName = _view.LastName

                            = _view.Address = _view.City = "";

                        _view.ErrorMessage

                            = "Contact not existing";

}

}

}

      else

      {

            _view.FirstName = _view.LastName =

            _view.Address = _view.City = "";

            _view.ErrorMessage = "Not a valid code!!!";

}

}


Presenter would implement therefore a method named SetCustomerData which task is to find a customer of a given code and update the view with resulting data. In case the entered code is not a valid number presenter would show appropriate message on validator that there is a syntax error. In case there are no contacts with a given code presenter should empty view and show a message that not existing code has been entered.

Illustration 9. Results of an example - Code 1 entered - user shown

Illustration 10. Results of an example - Non existing valid code entered

 

Illustration 11. Results of an example - Invalid code entered

Now I will show reuse of the presenter for implementing the same logic in totally different technology: WinForm

I'll slightly change the look by switching the places between search criteria and the error message and city would be presented now by ComboList

Illustration 12. UI look of the view made by windows form

Usage of MVP patterns allows me just to implement view interface to win form and to view up presenter by passing to its constructor WinForm and all the same functionality is present without touching a presenter. That's why the presenter is speaking to interface which shouldn't be technology specific

Illustration 13. Wiring up the win form view to the presenter

using System.Windows.Forms;

using Presenter;

namespace WinForm

{

    public partial class UserViewForm : Form, IUserView

    {

        private UserViewPresenter _presenter;

        public UserViewForm()

        {

            InitializeComponent();

            _presenter = new UserViewPresenter(this);

            _presenter.SetCustomerData();

        }

       

        private void searchButton_Click(object sender, System.EventArgs e)

        {

            _presenter.SetCustomerData();

        }

        #region IUserView Implementation

                  // The same implementation like in WebForm case

                  // Wire up the control text properties to interface members

        #endregion

    }

}

 

So the complete solution would be something like:

Illustration 13. Complete project tree

And the result is the same functionality encapsulated in presenter is been reused for a win form

Illustration 14. Results of an example in win form - Existing code entered

Illustration 15. Results of an example in win form - Non existing code entered

Illustration 16. Results of an example in win form - Invalid code entered

Conclusion

MVP is very powerful UI design pattern which has multiple benefits for developing all kinds of user interfaces. That is the reason why CAB (Composite Application Block) is using it as a one of basic UI building principles 

Attachments

Source code of the MVP application used in this example  

 

Published X 10 2006, 10:13 dop. by malovicn
Filed under:

Comments

 

VusCode - Coding dreams since 1998! said:

I've been very busy during the last couple weeks so I had only time for short posts about the cool and

ledna 19, 2007 5:02 odp.
 

VusCode - Coding dreams since 1998! said:

I'm having a Test Driven Development session here in Prague for the DNG (DotNetGroup). I'll speak about

ledna 20, 2007 7:31 odp.
 

VusCode - Coding dreams since 1998! said:

Introduction One of the coolest new things (at least for me) in IE 7 and Vista upcoming wave is redesigned

března 11, 2007 9:13 dop.
 

VusCode - Coding dreams since 1998! said:

Design patterns are set of best practices solutions to common problems. They are also an excellent dictionary

července 23, 2007 12:43 dop.
 

stephen said:

Best article I have read on the subject - nice1
září 15, 2007 8:03 odp.
 

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

října 17, 2007 11:50 dop.
 

tobsen said:

Well, I think you are combining the model with the presenter in your example. IMHO the logic of getting a costumer out of a xml file (or database or out of else where) doesn't belong to the responsiblity of the presenter but of the model. Also you are wiring the the presenter to the view within the view, thus making the the view depend on the presenter. Instead one might use another class (or even a DI-framwork) to inject the view into the presenter. just my 2cents...
října 17, 2007 4:54 odp.
 

malovicn said:

Tobsen,

I do agree with the first comment but disagree with the second one 

When I made the post I was more focused on the explaining the cooperation between the presenter and view on the most possible simple way and the way how presenter retrieves that data looked as a thing of side importance. But, you are right, presenter should delegate the call to the model (some service type or similar)

Regarding the second part...

The view up to the presenter is standard constructor type of DI pattern utilization for MVP pattern (I'm sure there are a lot of places which use the same c-tor DI thing)

I don't couple the presenter to the view (like you said), I couple the presenter with an interface of the view which means that any view implementing the view interface can work with the same presenter.

I don’t find that type of "coupling" is bringing any problems so I deliberately applied “view make direct calls the presenter” and moved away from Fowler original implementation “view publish event which presenter subscribes for” as to complex to be used in real world applications

I'm not sure what value would therefore bring another type injecting the view into the presenter, but I do know in case of the DI frameworks it would introduce unnecessary overkill of configuration files etc

října 17, 2007 5:10 odp.
 

VusCode - Coding dreams since 1998! said:

Mocking is term which describes programing technique mostly used in Test Driven Development for writing

října 20, 2007 11:26 dop.
 

tobsen said:

Well, I haven't worked that much with DI frameworks yet (I looked at Spring.Net and I know there is structure maps and I already downloaded Ninject...) so I can't tell if it is a "unnecessary overkill of configuration" for these frameworks. But I wonder how you actually test your UI-behaviour at all when you do it the way you described (e.g. instatiate the presenter in the view rather then injecting it). I also thought, before I read your comment, that it might be a good idea to be able to exchange the presenter if the need arises (a bug in the presenter has been fixed.. the logic of the presenter changed....) without recompiling the other parts (= the ui). I also thought that this is what DI-Frameworks can be used for. So maybe I am wrong and I won't even doubt that because I didn't do enough "real world applications" yet. So what I am going to do is l try to get an idea of what DI-Frameworks are made for and come back later to see if I have a better understanding of your procedure regarding the MVP pattern. regards tobsen.
listopadu 1, 2007 11:36 odp.
 

VusCode - Coding dreams since 1998! said:

Usually, usage of design patterns is associated with code executing in the lower tiers, but design patterns

listopadu 5, 2007 11:51 dop.
 

.NET Geek said:

The Model View Controller and Model View Presenter design pattern has been the source for a lot of confusion

listopadu 10, 2007 11:25 odp.
 

VusCode - Coding dreams since 1998! said:

What is Model View Presenter? MVP pattern is one of the major patterns used for extracting business logic

listopadu 19, 2007 9:15 odp.
 

JLinX - Blog » Blog Archive » Model View Presenter (MVP) design pattern said:

Pingback from  JLinX - Blog  &raquo; Blog Archive   &raquo; Model View Presenter (MVP) design pattern

prosince 11, 2007 4:49 odp.
 

Andrei Balan said:

Very nice article!

Small question - if you have to show another form after you do a search or after a user input - where is the best place to do it: in View or in Presenter?

The simple example is Login form.

I was thinking about having a function in IView called Redirect(string formName). The real redirect will be implemented in the view.

In Asp.Net it will be simple redirect and in Forms it will be creating a new Form and making it active instead of current.

What do you think?

Thank you,

Andrei Balan

března 10, 2008 5:46 odp.
 

rahul said:

THIS IS A TOTAL WASTE OF TIME...

března 31, 2008 10:30 dop.
 

Amer said:

Thanks alot .

května 12, 2008 2:32 odp.
 

Amer said:

Thanks alot .

května 12, 2008 2:32 odp.
 

diamond said:

I agree with tobson, the view becomes dependent to the presenter once you make a reference to it. I think the interfaces should be in a separate project. It will make the presenter unknown from the view and also the view from the presenter. Just an idea. I haven't yet applied MVP on a project. I'm still researching on this pattern.

Anyway good post.

června 30, 2008 3:54 odp.
 

malovicn said:

Diamond,

you can get what you are recommending (view ignorant of concrete presenter) without the interfaces. All you need is view raising the event and presenter subscribing to that event..

But, IMHO the key thing here is why view shouldn't know about presenter? Presenter is not having any purpose other to support the view. In MVP relationship between View and Presenter is almost always 1-1. In other words, I've never felt the need to "switch" different view presenters during the runtime

Every abstraction comes with a cost of decreased readability. That's why my personal opinion is that you should not add layers of indirection in case there is no "problem" which would be solved by that. Not following that principle IMHO leads to over-architected solutions

července 6, 2008 12:30 odp.
 

malovicn said:

Andrei,

I've seen couple of times having IView.RedirectTo(string) and in general it is perfectly fine solution for most use case scenarios.

Anyhow, I am just about to start MVP blog post series where one of the post would cover making of IHttpContextService which would provide to Presenter access to Redirect, Session, Cookies etc without th need of referencing System.Web into presenter assembly so this could maybe give you another idea on how to do this directly from presenter without the need to add any helpers to view

července 6, 2008 12:35 odp.
 

malovicn said:

re: how to test it when not injected

Tobsen,

the key point here is that you are testing only presenter and not the view. What happens in the view, you don't care. You can test presenter even not having at all view.

To test the presenter (in thise example) you would mock the IView to represent appropriate context state needed for test and you would test only presenter methods.

I would be covering this in more details in my upcoming MVP blog post series, but until then check out this post which have illustration on how to test MVP with rhino mocks

blog.vuscode.com/.../tdd-rhino-mocks-part-1-introduction.aspx

července 6, 2008 12:39 odp.
 

Krishna said:

About Illustration 5. View interface implementation, in which class i should we write the #region code and how it is associated with Customer.XML?

července 17, 2008 3:30 odp.
 

JobLot said:

malovicn,

cud u please throw some more light on making view ignorant of concrete presenter.

how would present subscribe to events raised by the view?

thanks

července 24, 2008 5:51 odp.
 

malovicn said:

JobLot,

if I understand you correctly what are you asking then check my other MVP example  which shows how view can raise an event instead of direct call to presenter method

blog.vuscode.com/.../model-view-presenter-mvp-design-pattern-close-look-part-1-passive-view.aspx

července 30, 2008 11:12 dop.
 

malovicn said:

Krishna,

at the bottom of the post (Attachments) you have source code which you can checkout

(The code goes to UserView.aspx.cs)

července 30, 2008 11:14 dop.
 

Shahriar_Sayed said:

Hi Malovic,

                Thanks for your simple, but helpful article about MVP pattern. Your article help me to understand MVP in a short time. Thanks again.

Shahriar Hasan Sayed

srpna 1, 2008 11:02 odp.
 

Ajay said:

Very nice article indeed. simple and sweet

srpna 13, 2008 5:18 odp.

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

Powered by Community Server (Non-Commercial Edition), by Telligent Systems NAVRCHOLU.cz