Search code examples
c#asp.net.netdesign-patternsmvp

Is this a valid MVP Pattern Implementation


I'm trying to analyse some code here that's been designed using an MVP Approach. No specific MVP Framework has been used. This is all hand-written code.

//Interface Representing our View
public interface IFooView
{
   string SomeScreenValue
}

//Presenter Implementation
public class FooPresenter 
{
    private readonly IFooView _view;

    public FooPresenter (IFooView view) 
    {
        //The presenter gets instantiated with a reference to a view.
        _view = view
    }

    public void SomeButton_Click(object sender, EventArgs e)
    {
        _view.SomeScreenValue = "The Result";
    }
}

//The Page Implementation
public class FooPage : System.Web.UI.Page, IFooView
{
    private FooPresenter _presenter;

    protected void Page_Init(...)
    {
        _presenter = new FooPresenter(this);  
        //<-- The View has a Presenter, which references the same View...
        Button1.Click += new EventHandler(_presener.SomeButton_Click);
    }
}

It works in that it allows the developer to move the business logic away from the code behind into classes, while still affecting the View. But the absense of an actual Model, and the way in which the View => Presenter => View relationship is setup is just a little irksome to me?

So is the above situation a valid implementation of the MVP Pattern ?


Solution

  • This is almost MVP in that your Presenter is de-coupled from the view in such a way that when it updates the UI state it does so through the IFooView interface. However, having a method within your presenter that conforms to a standard .NET event handler seems wrong to me. I would make IFooView raise an event when a button click occurs, then your page can perform the task of handling the button click as you currently do, then raising the event which your Presenter handles. This event can be more closely related to the domain, for example you might want an event such as RecordUpdated exposed via your IFooView.

    This will make it easier to provide a mock implementation of IFooView for unit testing, which is after all a big advantage of using an MVP / MVC / MVVM pattern.

    If you do not have any data coming from a back-end service, or database, then in the case of simple applications it is OK for the Presenter to take on the role of the model as well. This is the case in your trivial example. The same can be done in MVVM, where the ViewModel can take on the Model responsibilities also. However, I would recommend creating a Model if you do anything non-trivial. In your case, the Presenter would delegate to the Model for maintaining state and would use some sort of 'service' to persist changes to this model, or retrieve model objects from web services.