Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why using interface for Presenter in MVP?

I am going to learn MVP pattern using Professional ASP.NET Design Patterns. In presentation layer chapter it learn how to apply MVP to asp.net. The code for presenter is:

public class HomePagePresenter : IHomePagePresenter
{
   private IHomeView _view;
   private ProductService _productService;
   public HomePagePresenter(IHomeView view, ProductService productService)
   {
       _productService = productService;
       _view = view;
   }
   public void Display()
   {
        _view.TopSellingProduct = _productService.GetBestSellingProducts();
        _view.CategoryList = _productService.GetAllCategories();
   }
}

public interface IHomePagePresenter
{
    void Display();
}

The author said:

I have defined this (interface for HomePagePresenter) to loosely couple the code and to aid testing.

I can not understand how he will use presenter interface for creating tests? When I looked at nmock example they also does not created any interface for presenter.

like image 765
Seyed Morteza Mousavi Avatar asked Oct 21 '22 02:10

Seyed Morteza Mousavi


1 Answers

There are a number of reasons to expose your Presenters using interfaces:

  1. Polymorphism - you could have several IHomePagePresenter implementation and may use local context dependency injection resolution to determine which one to use at runtime.

  2. Mocking during testing - you could need to mock this particular Presenter for unit testing purposes and it's way easier to create a Mock against an interface than work with a concrete class. This really falls under polymorphism as well, but it's a concrete real-world example and loose-coupling. "Loose coupling" is basically being able to swap out the implementation of a class quickly and easily without having to change much/any code. The test scenario is that you are testing a Presenter class which may have a reference to another Presenter interface - you would mock the other Presenter object instead of using a concrete class.

  3. Method/property access restrictions - Interfaces restrict what parts of an implementation you can see/use, so for example if HomePagePresenter had a number of methods/proeprties that regular consumers of the class shouldn't use/have access to, you can restrict what they can use by exposing the class using the interface instead.

like image 66
toadflakz Avatar answered Oct 23 '22 05:10

toadflakz