MVP and MVC

This is the first post in series of three posts that discuss Model View Controller (MVC) and Model View Presenter (MVP) architectural patterns in context of Android development (part 2, part 3).

MVP and MVC in Android:

The motivation behind my research about MVP and MVC architectural patterns in Android had been best expressed by Robert “Uncle Bob” Martin:

The only way to make the deadline—the only way to go fast—is to keep the code as clean as possible at all times.Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

When I just started developing for Android, I got a feeling that Android frameworks were neatly designed and easy to use. However, the more I studied the more I got uncomfortable –  it is very easy to start developing for Android, but once you get to the non-trivial stuff, things tend to get very difficult. In part, this difficulty arises due to lack of proper documentation and official tutorials, but it also becomes clear, at some point, that Android framework does not encourage programmers to write a clean code (to say the least).

After struggling for a while, I realized that there must be a way to structure and decouple this spaghetti code of mine, therefore I searched Internet, read blogs, tried many different approaches myself and, finally, came up with a reasonably convenient architectural pattern for Android application. This pattern is based on the concepts introduced in another post – Why Activities in Android are not UI elements – and I encourage you to read it before proceeding any further.

Many ideas, concepts and some implementation details that this post and the associated tutorial application are built upon were presented by Josh (Whizzle) Musselwhite in his great blog, and Josh’s series of posts about Android architecture is among the best Android reading I’ve come across.

Model? View? Controller? Presenter?

MVC and MVP are architectural patterns (architectural patterns aim to provide kind of a “template” for organization of software system). The idea behind MVC and MVP is that many software systems can be divided into three independent components:

  • The component that stores system’s state (whether this state persistent or not). This component is referred to as Model.
  • The component that handles input-output from/to the client (the client might be a human user, but it doesn’t have to). This component is referred to as View.
  • The component that represents the logical functionality of the system, holds system’s “business rules”. This component is referred to as Controller/Presenter.

Components of a good MVC/MVP implementation should be decoupled as much as possible: it should be possible to switch from one input/output entity (View) to another, or to change the location or the type of persistent storage mechanism (Model) without affecting other components.

Benefits of a clean MVC/MVP implementation are:

  • Readable, understandable and maintainable code
  • Modular code which provides high degree of flexibility
  • More testable code (especially in context of unit testing)
  • Code which is way funnier to work with

In real material world the above benefits have a very strong correlation with faster time-to-market of new software projects and features, and with software that has fewer bugs. How cool is that!

What is the difference between MVC and MVP?

One big issue with these architectural patterns is that there is no universally agreed definition for them – you can find many descriptions on the web, some of which differ substantially. Therefore, before we begin our discussion, we shall omit any ambiguity by providing a concrete definition for each pattern. You’re invited to read this great post by Derek Greer – we will adopt his definition of MVC, but our notion of MVP corresponds to Derek’s description of “The passive view pattern”.

If you are curious to what extent can the definitions of MVC and MVP differ, you’re welcome to read this thread on StackOverflow.

Now let us put MVC and MVP (as defined earlier) interaction diagrams side by side and compare them:

 

MVC_MVP

As you can see, these architectural patterns are very similar. The key differences are:

  1. In MVC, the view gets notified of any change in model’s state by the model itself. The information about the actual change can be passed as part of the notification, or following the notification the view can query the model directly for the up to date data. In MVP, the view knows nothing about the model, and it is presenter’s job to fetch the up to date data from the model, understand whether the view should be updated and bind a new data to the view.
  2. As a consequence of #1, views in MVC tend to have more logic in them because they are responsible for handling of notifications and data processing. In MVP, the same logic is located in the presenter, which makes the views very “stupid” – their sole purpose becomes rendering data that was bound to them by the presenter (this is the reason why Derek Greer call this pattern “The passive view pattern” in his post).
  3. As a consequence of #1, models in MVC also have additional logic for handling interactions with the views. Some MVC implementations even put their business logic inside the models. As a contrast, good MVP model tends to just manage application’s data state and notify presenters of any change, nothing more.

The bottom line is this: in MVC the view is aware of model’s existence and they interact directly, whereas in MVP both the view and the model know nothing about each other.

Does Android support MVC or MVP natively?

The question is not whether the standard architecture for Android applications recommended by Google is MVC/MVP (currently, it is not as of 2016, MVP/MVC/MVVM became “buzz-words” in Android community due to being officially promoted by Google), but whether there is anything about Android that prevents developers from adopting these architectural patterns. After I experimented with these ideas for a while, I came to conclusion that some of the architectural aspects employed in Android violate the very basic principles of MVC/MVP.

The “M” part is fine – it is straightforward to implement a standalone model functionality in Android. In fact, ContentProvider accessible through ContentResolver makes for a very good MVC model once you get accustomed to it – a general, independent of the rest of the code approach, which completely abstracts the underlying storage mechanism. If the storage mechanism is SQLite database (which is very common), you even get thread safety “out of the box”. ContentResolver and ContentProvider also provide a built in implementation of URI based Observer design pattern. Combined with SyncAdapter framework, ContentProvider is a very versatile candidate for MVC model.

The problems arise if you try to separate view and controller functionality. For example, the following  code snippet was copied from Android Developers website:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Set the user interface layout for this Activity
    // The layout file is defined in the project res/layout/main_activity.xml file
    setContentView(R.layout.main_activity);

    // Initialize member TextView so we can manipulate it later
    mTextView = (TextView) findViewById(R.id.text_message);

    // Make sure we're running on Honeycomb or higher to use ActionBar APIs
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // For the main activity, make sure the app icon in the action bar
        // does not behave as a button
        ActionBar actionBar = getActionBar();
        actionBar.setHomeButtonEnabled(false);
    }
}

Let’s forget for a moment that this code snippet is trivial and analyze it through “view-controller prism” (i.e. in terms of view and controller functionality):

  • onCreate() is a “lifecycle” method which is called by Android framework in response to framework’s internal state transitions (these transitions might be related to user’s actions in the app,  but the app never calls onCreate() directly). You might get an impression that this method belongs to the “view” part of MVC because setContentView() is called along the way, but, in fact, setContentView() is a standard binding of a view performed by the controller. In addition, onCreate() (and other “lifecycle” methods) takes care of models initialization and binding, resources allocation and app’s state management. All these are controller’s functionality, which means that Activity (and, for the same reasons, Fragment) is the controller.
  • But wait – if Activity is the controller, then why does it directly manage the UI of the application? In the above example there are just two references to UI elements (R.layout.main_activity and R.id.text_message), but it is a widespread practice to describe all UI related functionality in Activity: configure the initial UI state, register/unregister action listeners, alter UI in response to user’s actions and/or model changes, etc… Doesn’t this functionality belong to view part of MVC? Maybe, after all, Activity is view?

Well, no. Activity (and Fragment) is bad candidate for MVC view – it is too tightly coupled with Android framework, and there is no other independent component which can take on the responsibility of controller. I summarized my thoughts about Activities in context of UI development in details in another post: Why Activities in Android are not UI elements.

The above discussion (and other factors) leads to the conclusion that Activity and Fragment are natural candidates for controllers, but, for some mysterious reason, Android framework is designed in such a way that Activity and Fragment also take on view responsibilities. This coupling is very strong in Android, and it is not trivial to enforce a complete separation of concerns when developing applications.

Which architectural pattern is more suitable for Android development – MVC or MVP?

We’ve already seen that MVC and MVP architectural patterns (as defined in this post) are very similar. Still, since we discuss Android development, there are aspects of Android framework which makes one of them a more suitable choice for application’s architecture. My personal opinion is that even though Android framework architecture is obviously bad in context of both MVC and MVP architectural patterns (and Single Responsibility Principle in general), it is still more natural and less error prone to employ MVP concept.

The reason why MVP is a more natural candidate for “clean” architecture in Android is that there is too much functionality associated with Activity/Fragment in Android, and the coupling between Activity/Fragment  and many Android frameworks and utilities is too strong, which makes the implementation of MVC views that can query the model directly harder and “dirtier”.

In the following parts of this post (part 2) I will describe one possible implementation of MVP in Android (the same one which is used in the tutorial app).

Please leave your comments and questions below, and consider subscribing to our newsletter if you liked the post.

This article has 8 comments

  1. Mahdi Pishguy Reply

    how about MVVM on Android? could you write useful post about it? which is better and we can simply manage Activity lifeCycle?

Leave a Comment

Your email address will not be published. Required fields are marked *