94

I am trying to implement the MVP method for the first time, using WinForms.

I am trying to understand the function of each layer.

In my program I have a GUI button that when clicked upon opens a openfiledialog window.

So using MVP, the GUI handles the button click event and then calls presenter.openfile();

Within presenter.openfile(), should that then delegate the opening of that file to the model layer, or as there is no data or logic to process, should it simply act on the request and open the openfiledialog window?

Update: I have decided to offer a bounty as I feel I need further assistance on this, and preferably tailored to my specific points below, so that I have context.

Okay, after reading up on MVP, I have decided to implement the Passive View. Effectively I will have a bunch of controls on a Winform that will be handled by a Presenter and then the tasks delegated to the Model(s). My specific points are below:

  1. When the winform loads, it has to obtain a treeview. Am I correct in thinking that the view should therefore call a method such as: presenter.gettree(), this in turn will delegate to the model, which will obtain the data for the treeview, create it and configure it, return it to the presenter, which in turn will pass to the view which will then simply assign it to, say, a panel?

  2. Would this be the same for any data control on the Winform, as I also have a datagridview?

  3. My App, has a number of model classes with the same assembly. It also supports a plugin architecture with plugins that need to be loaded at startup. Would the view simply call a presenter method, which in turn would call a method that loads the plugins and display the information in the view? Which tier would then control the plugin references. Would the view hold references to them or the presenter?

  4. Am I correct in thinking that the view should handle every single thing about presentation, from treeview node colour, to datagrid size, etc?

I think that they are my main concerns and if I understand how the flow should be for these I think I will be okay.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Darren Young
  • 10,972
  • 36
  • 91
  • 150
  • This link http://lostechies.com/derekgreer/2008/11/23/model-view-presenter-styles/ explains some of the styles of MVP. It could prove helpful in addition to Johann's excellent answer. – ak3nat0n Jun 01 '12 at 19:42

3 Answers3

131

This is my humble take on MVP and your specific issues.

First, anything that a user can interact with, or just be shown, is a view. The laws, behavior and characteristics of such a view is described by an interface. That interface can be implemented using a WinForms UI, a console UI, a web UI or even no UI at all (usually when testing a presenter) - the concrete implementation just doesn't matter as long as it obeys the laws of its view interface.

Second, a view is always controlled by a presenter. The laws, behavior and characteristics of such a presenter is also described by an interface. That interface has no interest in the concrete view implementation as long as it obeys the laws of its view interface.

Third, since a presenter controls its view, to minimize dependencies there's really no gain in having the view knowing anything at all about its presenter. There's an agreed contract between the presenter and the view and that's stated by the view interface.

The implications of Third are:

  • The presenter doesn't have any methods that the view can call, but the view has events that the presenter can subscribe to.
  • The presenter knows its view. I prefer to accomplish this with constructor injection on the concrete presenter.
  • The view has no idea what presenter is controlling it; it'll just never be provided any presenter.

For your issue, the above could look like this in somewhat simplified code:

interface IConfigurationView
{
    event EventHandler SelectConfigurationFile;

    void SetConfigurationFile(string fullPath);
    void Show();
}

class ConfigurationView : IConfigurationView
{
    Form form;
    Button selectConfigurationFileButton;
    Label fullPathLabel;

    public event EventHandler SelectConfigurationFile;

    public ConfigurationView()
    {
        // UI initialization.

        this.selectConfigurationFileButton.Click += delegate
        {
            var Handler = this.SelectConfigurationFile;

            if (Handler != null)
            {
                Handler(this, EventArgs.Empty);
            }
        };
    }

    public void SetConfigurationFile(string fullPath)
    {
        this.fullPathLabel.Text = fullPath;
    }

    public void Show()
    {
        this.form.ShowDialog();        
    }
}

interface IConfigurationPresenter
{
    void ShowView();
}

class ConfigurationPresenter : IConfigurationPresenter
{
    Configuration configuration = new Configuration();
    IConfigurationView view;

    public ConfigurationPresenter(IConfigurationView view)
    {
        this.view = view;            
        this.view.SelectConfigurationFile += delegate
        {
            // The ISelectFilePresenter and ISelectFileView behaviors
            // are implicit here, but in a WinForms case, a call to
            // OpenFileDialog wouldn't be too far fetched...
            var selectFilePresenter = Gimme.The<ISelectFilePresenter>();
            selectFilePresenter.ShowView();
            this.configuration.FullPath = selectFilePresenter.FullPath;
            this.view.SetConfigurationFile(this.configuration.FullPath);
        };
    }

    public void ShowView()
    {
        this.view.SetConfigurationFile(this.configuration.FullPath);
        this.view.Show();
    }
}

In addition to the above, I usually have a base IView interface where I stash the Show() and any owner view or view title that my views usually benefit from.

To your questions:

1. When the winform loads, it has to obtain a treeview. Am I correct in thinking that the view should therefore call a method such as: presenter.gettree(), this in turn will delegate to the model, which will obtain the data for the treeview, create it and configure it, return it to the presenter, which in turn will pass to the view which will then simply assign it to, say, a panel?

I would call IConfigurationView.SetTreeData(...) from IConfigurationPresenter.ShowView(), right before the call to IConfigurationView.Show()

2. Would this be the same for any data control on the Winform, as I also have a datagridview?

Yes, I would call IConfigurationView.SetTableData(...) for that. It's up to the view to format the data given to it. The presenter simply obeys the view's contract that it wants tabular data.

3. My App, has a number of model classes with the same assembly. It also supports a plugin architecture with plugins that need to be loaded at startup. Would the view simply call a presenter method, which in turn would call a method that loads the plugins and display the information in the view? Which tier would then control the plugin references. Would the view hold references to them or the presenter?

If the plugins are view-related, then the views should know about them, but not the presenter. If they are all about data and model, then the view shouldn't have anything to do with them.

4. Am I correct in thinking that the view should handle every single thing about presentation, from treeview node colour, to datagrid size, etc?

Yes. Think about it as the presenter providing XML that describes data and the view that takes the data and applies a CSS stylesheet to it. In concrete terms, the presenter might call IRoadMapView.SetRoadCondition(RoadCondition.Slippery) and the view then renders the road in red color.

What about data for clicked nodes?

5. If when I click on the treenodes, should I pass through the specific node to the presenter and then from that the presenter would work out what data it needs and then asks the model for that data, before presenting it back to the view?

If possible, I would pass all data needed to present the tree in a view in one shot. But if some data is too large to be passed from the beginning or if it's dynamic in its nature and needs the "latest snapshot" from the model (via the presenter), then I would add something like event LoadNodeDetailsEventHandler LoadNodeDetails to the view interface, so that the presenter can subscribe to it, fetch the details of the node in LoadNodeDetailsEventArgs.Node (possibly via its ID of some kind) from the model, so that the view can update its shown node details when the event handler delegate returns. Note that async patterns of this might be needed if fetching the data might be too slow for a good user experience.

Johann Gerell
  • 24,991
  • 10
  • 72
  • 122
  • 3
    I don't think that you necessarily have to decouple the view and the presenter. I usually decouple the model and the presenter, having the presenter listening to model events and act accordingly (update the view). Having a presenter in the view eases the communication between view and presenter. – kasperhj Jul 21 '11 at 19:33
  • 11
    @lejon: You say that *Having a presenter in the view eases the communication between view and presenter*, but I **strongly** disagree. My standpoint is this: When the view knows about the presenter, then for each **view event** the view must decide which **presenter method** is the proper one to call. That's "2 points of complexity", since the view doesn't really know which **view event** that corresponds to which **presenter method**. The contract doesn't specify that. – Johann Gerell Jul 21 '11 at 20:50
  • 5
    @lejon: If, on the other hand, the view only exposes the actual event, then the presenter itself (who knows what it wants to do when a view event occurs) just subscribes to it to do the correct thing. That's only "1 point of complexity", which in my book is twice as good as "2 points of complexity". Generally speaking, less coupling means less maintenance cost over the run of a project. – Johann Gerell Jul 21 '11 at 20:50
  • 10
    I too tend to use the encapsulated presenter as explained in this link http://lostechies.com/derekgreer/2008/11/23/model-view-presenter-styles/ in which the view is the sole holder of the presenter. – ak3nat0n Jun 01 '12 at 19:40
  • 4
    @ak3nat0n: With respect to the three styles of MVP explained in the link you provided, I believe this answer by Johann might be most closely aligned with the third style which is named **Observing Presenter Style**: *"The benefit of the Observing Presenter style is that it completely decouples knowledge of the Presenter from the View making the View less susceptible to changes within the Presenter."* – DavidRR Aug 11 '15 at 15:26
12

The presenter, which contains all logic in the view, should respond to the button being clicked as @JochemKempe says. In practical terms, the button click event handler calls presenter.OpenFile(). The presenter is then able to determine what should be done.

If it decides that the user must select a file, it calls back into the view (via a view interface) and let the view, which contains all UI technicalities, display the OpenFileDialog. This is a very important distinction in that the presenter should not be allowed to perform operations tied to the UI technology in use.

The selected file will then be returned to the presenter which continues its logic. This may involve whatever model or service should handle processing the file.

The primary reason for using an MVP pattern, imo is to separate the UI technology from the view logic. Thus the presenter orchestrates all logic while the view keeps it separated from UI logic. This has the very nice side effect of making the presenter fully unit testable.

Update: since the presenter is the embodiment of the logic found in one specific view, the view-presenter relationship is IMO a one-to-one relationship. And for all practical purposes, one view instance (say a Form) interacts with one presenter instance, and one presenter instance interacts with only one view instance.

That said, in my implementation of MVP with WinForms the presenter always interacts with the view through an interface representing the UI abilities of the view. There is no limitation on what view implements this interface, thus different "widgets" may implement the same view interface and reuse the presenter class.

Community
  • 1
  • 1
Peter Lillevold
  • 33,668
  • 7
  • 97
  • 131
  • Thanks. So in the presenter.OpenFile() method, it should not have the code to show the openfiledialog? Instead it should go back into the view for that to show that window? – Darren Young Jan 25 '11 at 15:10
  • 4
    Right, I would never let the presenter open dialog boxes directly, since that would break your tests. Either offload that to the view or, as I've done in some scenarios, have a separate "FileOpenService" class handle the actual dialog interaction. That way you can fake the file opening service during tests. Putting such code in a separate service may give you nice re-usability side effects :) – Peter Lillevold Jan 25 '11 at 15:19
2

The presenter should act on the request end show the openfiledialog window as you suggested. Since no data is required from the model the presenter can, and should, handle the request.

Let's assume you need the data to create some entities in your model. You can either pass the stream trough to the access layer where you have a method to create entities from the stream, but I suggest you handle the parsing of the file in your presenter and use a constructor or Create method per entity in your model.

JochemKempe
  • 2,566
  • 2
  • 16
  • 12
  • 1
    Thanks for the response. Also, would you have a single presenter for the view? And that presenter either handles the request, or if data is required, then it delegates to any number of model classes that act upon the specific requests? Is that the correct way ? Thanks again. – Darren Young Jan 25 '11 at 14:36
  • 3
    A View has one presenter but a presenter can have multiple views. – JochemKempe Jan 25 '11 at 15:06