Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Differences between MVC and MVP for Beginners

4.89/5 (42 votes)
23 Nov 2011CPOL7 min read 271.4K   3K  
This article aims to describe MVC and MVP in simple terms

Introduction

In the modern world, an architect who can engineer an efficient decoupled system is considered as an invaluable asset to the company. This is because a decoupled system will lower the maintenance costs and help the developers to make quick alterations to the program without affecting the overall system. A decoupled system promotes parallel development, meaning work can be divided among different developers which will cut short the development time significantly. In this article, I explain about the two most popular patterns used for developing decoupled systems. They are called Model View Controller (MVC) and Model View presenter (MVP).

I have based my explanations on desktop application development.

(M)odel (V)iew (C) ontroller

Image 1

MVC architecture is one of the oldest patterns available for achieving the separation of concerns. MVC consists of three layers, viz, Model, View, and Controller.

Classic MVC existed at a time when every control/gadget that existed in the screen was considered dumb and each control is paired with its own controller to manage the user interactions happening on them. So if 10 gadgets exist, then 10 controllers have to exist. In this scenario, every gadget is counted as a view. The advent of Windows GUI systems changed this picture. The Control-Controller relationship became obsolete. Controls gained the intelligence to respond to the actions initiated by the user. In the Windows world, view is a surface on which all the controls/gadgets exist, hence there is a need for only one controller. View can receive events and reach for controllers help to do further processing.

Model – Model receives input from the controller and decides what data it needed to fulfill the request raised by the controller. Model is also capable of doing transactions with databases or other persistent storage as needed. Once it gathers the required information, it informs the view (via controller) about the new data by raising appropriate events.

View – View hosts all the UI controls needed by the end-user to interact with the application. Its job is to monitor end-user gestures and pass it to the controller for further handling. View handles the event notification received from the Model and may request for any new data required to render it on the screen. However, in some variations, Controller can be designated to retrieve dataset from the Model, format it and send it to the View. Here the view’s job is to render the data received from the view without any other processing.

Controller – Controller can be imagined as an extension or a personal assistant to the view, all the events originated from the view is handled by the controller. Controller will also inform the Model on behalf of view that some event happened on the view and some new data might be required.

C#
public Controller(IViewBase view)
    {
        _view = view;
        _model.ModelChanged += new EventHandler(_model_ModelChanged);    
    }

Normally, controller’s constructor accepts the view as a parameter. Controller will make use of this parameter to access view’s methods. As you can see, controller is subscribing to the ModelChanged event. This event is raised when a model’s state has changed. Controller traps this event to inform the view that models state has changed.

(M)odel (V)iew (P)resenter

Image 2

A MVP system is an evolved version of MVC. In this pattern, view receives the UI events and calls the presenter as needed. Presenter is also responsible for updating the view with the new data generated by the model.

Model - Model can be thought of as the interface to the data. Any part of the program which needs some data to work on must go through the interface or functions defined by the developer who is maintaining the model part. Typically, model houses all the validation routines for the data submitted by the end user

View – View, as the name implies, is the part where end user interacts. The development of this part can be delegated to a specialized designer. A program may have any number of views.

Presenter – Presenter acts as an intermediary to make the decoupling possible. All the business logic required for responding to a user event is written inside the Presenter layer. Typically the view only has the event handler and the logic to call the appropriate presenter functions, helping the person working on the view to concentrate upon designing the user interface without worrying about the code behind file. Presenter is also responsible for retrieving the requested data from the model and formats it so that the view can render it without any overhead.

MVP is the successor of MVC and one of the popular design patterns used in the .NET world to build a decoupled system. System designed with MVP pattern also promotes unit testing making your program rock solid.

Defining Communication Interface

In order to make MVP work, an interface or contract must have to define for Model and the View so that the Presenter knows which function to call when.

C#
interface  IStudentModel
    {
        void Save(string username,string email );
        string Get(string username);
        bool ValidateEmail(string email);
        bool IsEntryExisting(string username);
    }

interface IStudentView
    {
        String UserName { get; set; }
        String Email { get; set; } 

    }

Typically, a presenter class’ constructor will accept the View and Model as parameters. Once this information is passed to the Presenter, it is responsible for any communication between view and model. The dependency injection feature of the Presenter assists unit testing with mock objects.

MVP Passive view v/s MVP Supervising Controller

MVP (Supervising Controller) is another variation of MVP pattern. Unlike MVP (passive view) which is explained above, the view in MVP (SC) is more intelligent. View will have the ability to talk directly with Model and query for data as needed. Presenter’s job is to inform the model that certain activity has occurred in the view which may result in change of state. Presenter also passes a reference to model so that view can interact with model directly whenever model’s state changes. In short, MVP (SC) is similar to MVC in most of its aspects.

Difference Table

Image 3

Duties Table

Image 4

MVC

Image 5

MVP

MVC/MVP FAQ

Q) I believe all UI modification (such as changing the text forecolor when a threshold is met) needs to be done in the view level as the model does not have any direct contact with controller. Is this correct?

A) Yes. If view is directly retrieving the new data from the Model.

No. If view is seeking controllers' help to query the new data. In this case, the controller can format the data and send it to the view.

Q) I see a dotted line connecting the model to view indicating an 'indirect' relationship. Can you please explain what is that indirect relationship means?

The model does not know the view, but the view knows the model.

Q) I’ve seen objects like interactors, commands, selections in some MVP explanations. When should I use that?

A) These objects existed in Mike Potel’s MVP in such age when the user controls and GUI were not developed like today. In current windows world, we can very well execute a MVP pattern without the objects mentioned in the question.

Please keep in mind that design patterns are loose guidelines which help you to solve common problems. It is not necessary to strictly follow a design pattern to the core. You may tweak a design pattern as per your need.

Q) What is the benefit of having a presenter? - Why can't the view talk to the model immediately?

A) The basic idea behind the MVP pattern is separation of concerns. This improves testability and mock objects can be introduced to test the domain part. Besides that, we can change the views which can represent the model data differently.

Q) Where should I write validation in MVC/MVP architecture?

A) The basic control validations like empty field validation should be done at view level. Anything concerning the database should be written inside the model as public methods. This method will be consumed by the Controller to do the validation before the data reaches the Model.

History

  • 23rd November, 2011: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)