Wednesday, 23 December 2020

Model-View-ViewModel (MVVM) & MVC & MVP

 

Model–view–viewmodel (MVVM) is a software architectural pattern that facilitates the separation of the development of the graphical user interface (the view) – be it via a markup language or GUI code – from the development of the business logic or back-end logic (the model) so that the view is not dependent on any specific model platform. The view model of MVVM is a value converter, meaning the view model is responsible for exposing (converting) the data objects from the model in such a way that objects are easily managed and presented.  




--Ref : "wikipedia"


DESCRIPTION OF MODEL :


MODEL: ( Reusable Code – DATA ) Business Objects that encapsulate data and behavior of application domain, Simply holds the data.
VIEW: ( Platform Specific Code – USER INTERFACE ) What the user sees, The Formatted data.
VIEWMODEL: ( Reusable Code – LOGIC ) Link bewteen Model and View OR It Retrieves data from Model and exposes it to the View. This is the model specifically designed for the View.

FEATURES:

  • Life Cycle state of Application will be maintained.
  • The application will be in the same position as to where the user left it.
  • UI Components are kept away from Business Logic.
  • Business Logic is kept away from Database operations.
  • Easy to understand and read.

  • Get some more details : 

The Model

The model is what I like to refer to as the domain object. The model represents the actual data and/or information we are dealing with. An example of a model might be a contact (containing name, phone number, address, etc) or the characteristics of a live streaming publishing point.

The key to remember with the model is that it holds the information, but not behaviors or services that manipulate the information. It is not responsible for formatting text to look pretty on the screen, or fetching a list of items from a remote server (in fact, in that list, each item would most likely be a model of its own). Business logic is typically kept separate from the model, and encapsulated in other classes that act on the model.

This is not always true: for example, some models may contain validation.

It is often a challenge to keep a model completely “clean.” By this I mean a true representation of “the real world.” For example, a contact record may contain a last modified date and the identity of the modifying user (auditing information), and a unique identifier (database or persistence information). The modified date has no real meaning for a contact in the real world but is a function of how the model is used, tracked, and persisted in the system.

Here is a sample model for holding contact information:

namespace MVVMExample
{
    public class ContactModel : INotifyPropertyChanged
    {
        private string _firstName;

        public string FirstName
        {
            get { return _firstName; }
            set
            {
                _firstName = value;
                RaisePropertyChanged("FirstName");
                RaisePropertyChanged("FullName");
            }
        }

        private string _lastName;

        public string LastName
        {
            get { return _lastName; }
            set
            {
                _lastName = value;
                RaisePropertyChanged("LastName");
                RaisePropertyChanged("FullName");
            }
        }

        public string FullName
        {
            get { return string.Format("{0} {1}", FirstName, LastName); }
        }

        private string _phoneNumber;

        public string PhoneNumber
        {
            get { return _phoneNumber; }
            set
            {
                _phoneNumber = value;
                RaisePropertyChanged("PhoneNumber");
            }
        }

        protected void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public override bool Equals(object obj)
        {
            return obj is ContactModel && ((ContactModel) obj).FullName.Equals(FullName);
        }

        public override int GetHashCode()
        {
            return FullName.GetHashCode();
        }
    }
}

The View

The view is what most of us are familiar with and the only thing the end user really interacts with. It is the presentation of the data. The view takes certain liberties to make this data more presentable. For example, a date might be stored on the model as number of seconds since midnight on January 1, 1970 (Unix Time). To the end user, however, it is presented with the month name, date, and year in their local time zone. A view can also have behaviors associated with it, such as accepting user input. The view manages input (key presses, mouse movements, touch gestures, etc) which ultimately manipulates properties of the model.

In MVVM, the view is active. As opposed to a passive view which has no knowledge of the model and is completely manipulated by a controller/presenter, the view in MVVM contains behaviors, events, and data-bindings that ultimately require knowledge of the underlying model and viewmodel. While these events and behaviors might be mapped to properties, method calls, and commands, the view is still responsible for handling it’s own events and does not turn this completely over to the viewmodel.

One thing to remember about the view is that it is not responsible for maintaining its state. Instead, it will synchronize this with the viewmodel.

Here is an example view, expressed as XAML:

<UserControl x:Class="MVVMExample.DetailView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding CurrentContact}">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="Name:" HorizontalAlignment="Right" Margin="5"/>
        <TextBlock Text="{Binding FullName}" HorizontalAlignment="Left" Margin="5" Grid.Column="1"/>
        <TextBlock Text="Phone:" HorizontalAlignment="Right" Margin="5" Grid.Row="1"/>
        <TextBlock Text="{Binding PhoneNumber}" HorizontalAlignment="Left" Margin="5" Grid.Row="1" Grid.Column="1"/>
    </Grid>
</UserControl>

Note that the various bindings are the integration/synchronization points with the viewmodel.

The ViewModel (Our Controller/Presenter)

The viewmodel is a key piece of the triad because it introduces Presentation Separation, or the concept of keeping the nuances of the view separate from the model. Instead of making the model aware of the user’s view of a date, so that it converts the date to the display format, the model simply holds the data, the view simply holds the formatted date, and the controller acts as the liaison between the two. The controller might take input from the view and place it on the model, or it might interact with a service to retrieve the model, then translate properties and place it on the view.

The viewmodel also exposes methods, commands, and other points that help maintain the state of the view, manipulate the model as the result of actions on the view, and trigger events in the view itself.

Here is what a sample view model might look like. We’ve created a BaseINPC class (for “INotifyPropertyChanged”) that has a method to make it easy for raising the property changed event.

namespace MVVMExample
{
    public class ContactViewModel : BaseINPC
    {
        public ContactViewModel()
        {
            Contacts = new ObservableCollection<ContactModel>();
            Service = new Service();
            
            Service.GetContacts(_PopulateContacts);

            Delete = new DeleteCommand(
                Service, 
                ()=>CanDelete,
                contact =>
                    {
                        CurrentContact = null;
                        Service.GetContacts(_PopulateContacts);
                    });
        }

        private void _PopulateContacts(IEnumerable>ContactModel> contacts)
        {
            Contacts.Clear();
            foreach(var contact in contacts)
            {
                Contacts.Add(contact);
            }
        }

        public IService Service { get; set; }

        public bool CanDelete
        {
            get { return _currentContact != null; }
        }

        public ObservableCollection<ContactModel> Contacts { get; set; }

        public DeleteCommand Delete { get; set; }

        private ContactModel _currentContact;

        public ContactModel CurrentContact
        {
            get { return _currentContact; }
            set
            {
                _currentContact = value;
                RaisePropertyChanged("CurrentContact");
                RaisePropertyChanged("CanDelete");
                Delete.RaiseCanExecuteChanged();
            }
        }
    }
}

This view model is obviously designed to manage a list of contacts. It also exposes a delete command and a flag to indicate whether delete is allowed (thus maintaining state for the view). Often the flag would be part of the command object, but the example is in Silverlight 3 which does not have native support for command binding, and I wanted to show a simple solution that didn’t require a fancy framework. The view model here makes a concrete reference to the service, you would most likely wire in that reference externally or use a dependency injection framework. What’s nice is we have the flexibility to build it like this initially and then refactor as needed. It fetches the list of “contacts” right away, which is a hard-coded list of me and someone a little more popular. The phone numbers, of course, are faked.

The View and the ViewModel

  • The view and the viewmodel communicate via data-binding, method calls, properties, events, and messages
  • The viewmodel exposes not only models, but other properties (such as state information, like the “is busy” indicator) and commands
  • The view handles its own UI events, then maps them to the viewmodel via commands
  • The models and properties on the viewmodel are updated from the view via two-way databinding.

DIFFERENCES BETWEEN MVVM AND MVC:

MVVMMVC:
The Model is somewhat similar to MVC but here we have ViewModels which are passed to the view and
all the logic is in the ViewModel and hence no controller is there. Example: Knockout.js
In this pattern, we have models which are basic objects with no code and just properties, View’s
contributes to presentation items (HTML, WinForms, etc) and Controllers focuses on the logic part.
Examples: ASP.NET MVC, Angular
In MVVM your DeletePerson would be called off of your view modelWe have a PersonController with an Action DeletePerson that creates a person
We are on the client side so we can hold on to objects and do a lot more logic in a non-disconnected
state.
MVC is typically used when things are transactional and disconnected as is the case with server-side
web. In ASP MVC we send the view through the wire and then the transaction with the client is over.

ADVANTAGES:

  • Maintainability – Can remain agile and keep releasing successive versions quickly.
  • Extensibility – Have the ability to replace or add new pieces of code.
  • Testability – Easier to write unit tests against a core logic.
  • Transparent Communication – The view model provides a transparent interface to the view controller, which it uses to populate the view layer and interact with the model layer, which results in a transparent communication between the layers of your application.

DISADVANTAGES:

  • Some people think that for simple UIs, MVVM can be overkill.
  • In bigger cases, it can be hard to design the ViewModel.
  • Debugging would be a bit difficult when we have complex data bindings.

MVP :


MVP stands for Model View Presenter, and the MVP pattern is the successor of the MVC (Model View Controller) model. In simple words,  
" the MVP is the much-awaited update with a better user interface and was redesigned for smoother code modification ."

The MVP pattern is further divided into three different layers, which are: Model, Presenter, and View.

1. Model

The first layer is the Model that contains the data; we can say that the model is the only gateway to the business logic as they merely store the data. These models are treated as objects because they also consist of properties including details like Name, Type, Date and many more.

The model layer stores the JavaBeans data from several sources like the cache, android file system, database, etc.

2. Presenter

The second layer is that of the Presenter, which is also known as the middle-man between the two other layers. So, the part coupling between the Model layer and the View layer is the Presenter layer. The responsibility of the presenter layer is to pass the data from one layer to another by analyzing it and providing interaction between the layers.

The division of the Presenter layer is responsible for allowing the substitution of the coding parts, connecting layers as interfaces, and also the proper testing.

3. View

The third and the last layer is the View layer whose responsibility is to provide the visual display of the mobile apps in sync with the data and information that is provided as input by the user. The critical function of the view layer is first to detect the input, if any and then proceed with visualization based on actions like swipe, tap, touch, etc.

The view layer is to take care of the UI component which further controls the viewing properties and is responsible for displaying the data on the screen.

Pros of MVP Pattern

  • MVP has better testing possibilities because here the complete business logic is separated from the UI segment and that's why the data is more straightforward to imitate.
  • The view layer in this architecture is comparatively light as it has few clear lines of code just to support visualization.
  • Unlike other architecture, the developer can easily change the framework because in MVP all the ties are described in the form of interfaces.

Cons of MVP Pattern

  • The size of the code in Model View Presenter (MVP) is excessive which further makes it a little bit complex.
  • In the MVP architecture, a large number of interfaces are used for interaction between the three layers.
  • Because each interface only covers a small fraction of the interactions, this leads to a large variety of methods to implement.

Reasons to Pick MVVM in the MVP vs. MVVM Comparison

Below is the comparison between the MVP and the MVVM architectures based on the features like:

  • Logic: In the MVVM model, the code class of ViewModel is the application, and its View is the interface between the user and the app for the interaction purpose. Whereas in the case of MVP, the View is the app and the Presenter is handling the flow of the application.
  • Data Input: The process in MVP initiated from the View and not with the Presenter, but in the case of MVVM, it begins with View and not from the ViewModel.
  • Maintainability: It is easy to add new features in the ViewModel if the app developer has some prior experience with the particular library.
  • Code Metrics: The Model View Presenter creates more code and Java classes than the ViewModel architecture.

We favor MVVM over the MVP model because in the MVVM pattern the separation is possible between the View layer and the ViewModel that means a separation can exist between the User Interface (UI) and the logical code respectively.

The app developers can also write their UI tests by using Expresso which is highly preferred. But the best part about MVVM that makes it a more attractive option than MVP is that it provides the ease of maintenance to the user by allowing them to make changes to codebase efficiently.

So, that was our shot in comparison of two of the most popular android app development architectures, i.e., MVP vs. MVVM models. Hopefully, you liked the insights on the main difference between the MVP vs. MVVM android architecture model.



4 comments:

All About .NET MAUI

  What’s .NET MAUI? .NET MAUI (.NET Multi-platform App UI) is a framework for building modern, multi-platform, natively compiled iOS, Androi...

Ads2