Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4536

Difference Between MVC and MVP Patterns

$
0
0

1. Overview

In this tutorial, we'll learn about the Model View Controller and Model View Presenter patterns. We'll also discuss the differences between them.

2. Design Pattern and Architectural Pattern

2.1. Architectural Pattern

Architectural patterns are general, reusable solutions to commonly occurring problems in software architecture. These have an extensive impact on the codebase.

For example, these impact the software either horizontally or vertically. By horizontally, we mean how to structure the code inside a layer. Conversely, vertically means how a request is processed from outer layers to inner layers and back.

Some of the more common architectural patterns are MVC, MVP, and MVVM.

2.2. Design Pattern

Design patterns are usually associated with code-level commonalities. They provide various schemes for refining and building smaller subsystems.

Additionally, design patterns are medium-scale tactics that flesh out some of the structure and behavior of entities and their relationships. Some commonly used design patterns are the singleton, factory, and builder patterns.

Design Patterns differ from Architectural Patterns in their scope. They're more localized and have less impact on the codebase. Instead, they impact only a specific section of the codebase. In the next section, we'll talk about why we use these patterns.

3. Why MVC and MVP Patterns

The main idea behind the use of these patterns is the separation of concerns between the business and UI layers. These patterns provide us with features like ease of testing. They also hide data access.

We can say they're more adaptable to change by isolating the major components. However, the biggest drawbacks are adding complexity and the learning curve.

4. MVC Pattern

In the MVC pattern, features are divided into three components based on three separate concerns. Firstly, the view is responsible for rendering UI elements. Secondly, the controller responds to UI actions. And the model handles business behaviors and state management.

In most implementations, all three components can directly interact with each other. However, in some implementations, the controller is responsible for determining which view to display.

The diagram below shows the MVC flow of control:

The model represents the whole business logic layer. The view represents the data fetched from the model. In addition, it handles presentation logic. Lastly, the controller handles control flow logic and updates the model.

MVC doesn't specify how the view and the model should be structured internally. Usually, the view layer is implemented in a single class.

However, in that case, a couple of problems can arise:

  • The view and the model are tightly coupled. As a result, feature requirements of the view can easily drip down to the model and pollute the business logic layer
  • The view is monolithic and usually couples tightly with the UI framework. Thus, unit testing the view becomes difficult

5. MVP Pattern

The MVP pattern is a UI presentation pattern based on the concepts of the MVC pattern. However, it doesn't specify how to structure the whole system. It only dictates how to structure the view.

This pattern separates responsibilities across four components in general. Firstly the view is responsible for rendering UI elements. Secondly, the view interface is used to loosely couple the presenter from its view.

Finally, the presenter interacts with the view and model, and the model is responsible for business behaviors and state management.

In some implementations, the presenter interacts with a service (controller) layer to retrieve/persist the model. The view interface and service layer are commonly used to make writing unit tests for the presenter and the model easier.

The diagram below shows the MVP flow of control:

mvp_pattern

The model is the same as in MVC and contains the business logic. The view is a passive interface that displays data. It sends user actions to the presenter.

The presenter sits between the model and view. It triggers business logic and enables the view to update. It receives data from the model and shows the same in the view. This makes testing the presenter much easier.

Still, there are some problems with MVP:

  • The controller is often omitted. Because of the lack of a controller, control flow has also to be handled by the presenter. This makes the presenter responsible for two concerns: updating the model and presenting the model
  • We can't utilize data binding. If binding is possible with the UI framework, we should utilize it to simplify the presenter

6. MVC and MVP Implementation

We'll understand the patterns with a simple example. We've got a product that we need to show and update. These actions are handled differently in MVC and MVP.

6.1. The View Class

We have a simple view class that outputs the product details. The view class for both MVP and MVC are similar:

public class ProductView {
    public void printProductDetails(String name, String description, Double price) {
        log.info("Product details:");
        log.info("product Name: " + name);
        log.info("product Description: " + description);
        log.info("product price: " + price);
    }
}

6.2. MVP Model and Presenter Classes

Let's now define a Product class for MVP that is responsible for the business logic only:

public class Product {
    private String name;
    private String description;
    private Double price;
    
   //getters & setters
}

The presenter class in MVP fetches the data from the model and passes it to the view:

public class ProductPresenter {
    private final Product product;
    private final ProductView view;
    
     //getters,setters & constructor
    
    public void showProduct() {
        productView.printProductDetails(product.getName(), product.getDescription(), product.getPrice());
    }
}

6.3. MVC Model Class

For MVC, the difference is that the view will get the data from the model class instead of the presenter class in MVP.

We can define a model class for MVC:

public class Product {
    private String name;
    private String description;
    private Double price;
    private ProductView view;
    
    //getters,setters
    
    public void showProduct() {
        view.printProductDetails(name, description, price);
    }
}

Notice the showProduct() method. This method handles the data passing from model to view. In MVP, this is done in the presenter class, and in MVC, it's done in the model class.

7. Comparison Between MVC and MVP

There aren't a whole lot of differences between MVC and MVP. Both patterns focus on separating responsibility across multiple components, hence, promoting loose coupling of the UI (View) from the business layer (Model).

The major differences are how the patterns are implemented and in some advanced scenarios. Let's look at some of the key differences:

  • Coupling: The view and the model are tightly coupled in MVC but loosely coupled in MVP
  • Communication: In MVP, communication between the View-Presenter and Presenter-Model happens via an interface. However, the controller and view layer falls in the same activity/fragment in MVC
  • User Input: In MVC, user inputs are handled by the Controller that instructs the model for further operations. But in MVP, user inputs are handled by the view that instructs the presenter to call appropriate functions
  • Type of Relation: A many-to-one relationship exists between the controller and view. One Controller can select different views based upon required operations in MVC. On the other hand, the presenter and view have a one-to-one relationship in MVP, where one presenter class manages one view at a time
  • Main Component: In MVC, the controller is in charge. It creates the appropriate view and interacts with the model according to the user’s request. On the contrary, in MVP, the view is in charge. The view call methods on the presenter, which further directs the model
  • Unit Testing: Due to tight coupling, MVC has limited support for unit testing. On the other hand, unit Testing is well supported in MVP

8. Why MVP Has an Edge over MVC

MVP has the slight upper hand over MVC in that it can break down our application into modules. Thus, we can avoid having to create views constantly. In other words, MVP can help to make our views reusable.

9. Conclusion

In this tutorial, we've seen the MVC and MVP architectural patterns and a comparison between them.

The example code is available over on GitHub.

The post Difference Between MVC and MVP Patterns first appeared on Baeldung.
       

Viewing all articles
Browse latest Browse all 4536

Trending Articles