This post opens a series of articles about Model View Controller (MVC) and Model View Presenter (MVP) architectural patterns in context of Android development.

Why you should be interested in MVP and MVC:

Consider this statement 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

Proper MVP and MVC implementations have the following characteristics:

  • Readable and maintainable code
  • Modular code which provides high degree of decoupling
  • More testable code
  • Code which is fun to work with

The above characteristics are generally associated with “clean code”. Therefore, following Uncle Bob’s reasoning, adoption of MVP or MVC allows us to go faster.

History and credits:

Android development used to be a mess.

Historically, the platform was poorly designed and there were absolutely no design guidelines as to how Android applications should be built. Official tutorials demonstrated how to put all applications’ logic inside Activities and Fragments, and so developers did.

Surely enough, this approach led to ever-growing classes that had thousands upon thousands of lines of code inside them.

Slowly, as community members got hands on experience with the platform, better ways to write applications emerged. The idea of separating UI logic from the rest of the application long predates Android, but it took some time until it penetrated into the community of Android developers and became widespread.

The earliest article that I could find which discusses presentation layer architectures in Android dates back to November 2010. It is titled Android Architecture: Message-based MVC and was published by Ivan Memruk on his blog Mind The Robot.

Though the article is very old and the messaging technique that Ivan used is probably non-optimal by today’s standards, the fundamental structure is exactly what we call MVP in Android community today.

While I’m not sure that Ivan was actually the first one to write about presentation layer architectures in Android, this post was a huge step forward and an inspiration for other community members.

In November 2011, Josh Musselwhite writes a series of 9(!) posts titled Android Architecture. In this series Josh expands upon Ivan’s ideas and polishes some implementation details.

That could be the end of the story, but, fortunately, it wasn’t.

In July 2012 Josh writes 10th post in the series titled The Activity Revisited. In this post Josh revolutionized Android development by expressing the idea that Activity is not a view in MVC, but a controller.

I read Ivan’s and Josh’s articles in 2014, during my own quest after a good architectural pattern for presentation layer in Android, and was immediately sold. Since then I developed these ideas further and summarized what I learned and did in several articles of my own.

The article Activities in Android are not UI Elements explains why Activities should not contain UI logic and naturally fit into controllers role.

This series of posts demonstrates how to actually implement a solid MVC architectural pattern in Android.

The most mature architectural pattern for Android development:

In the previous section I told you how I learned what I’m about to share with you in this and the following articles.

Before we deep dive into software design, however, I’d like you to note that architectural pattern that you’re about to see was developed and polished since 2010 by at least three independent professionals.

This makes this architectural pattern the most mature and time tested approach to developing Android applications.

Outline:

Part 1 of the series (this post) will provide a general definitions of MVP and MVC architectural patterns, followed by discussion of applicability of MVP and MVC in context of Android development.

Part 2 of the series is all about “view” component. It shows how to properly abstract application’s user interface by extracting UI logic into standalone, independent classes.

Part 3 of the series discusses “presenter/controller” component.

Core concepts and techniques will be presented using fully functional open-source tutorial application. This application was written for the sole purpose of demonstrating the power of clean MVP/MVC implementation.

There is also a real world open-sourced application that uses the approach described in this series of posts. Source code of this application can serve as a “reference” for more advanced cases than those presented in tutorial app (e.g. Navigation Drawer).

Model? View? Controller? Presenter?

MVP and MVC are architectural patterns. The idea behind them is that many software systems that have user interface can be divided into three 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 user. This component is referred to as View.
  • The component that encapsulates the logical functionality of the system. 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.

What is the difference between MVC and MVP?

Unfortunately, there is no universally agreed definition for either MVC or MVP. 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.

If you are curious to what extent can the definitions of MVC and MVP by different people differ – read this thread on StackOverflow.

Interested readers might also read this great post by Derek Greer – we will fully adopt his definition of MVC, but our notion of MVP will correspond to Derek’s “the passive view pattern”.

Now let us put MVC and MVP 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. 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. Views in MVC tend to have more logic in them because they are responsible for handling of notifications from the model. In MVP, the same logic is located in the presenter, which makes the views very “dumb” – their sole purpose becomes rendering of the data that was bound to them by the presenter and capturing user input.

The bottom line is that 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, some variations of MVx patterns became officially promoted by Google). The question is whether there is anything about Android that prevents developers from adopting these architectural patterns.

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 ContentProvider is too complex or restricting for application’s needs, a good model can also be implemented using one of the existing persistence libraries (e.g. ORM libraries) , or using custom global in-memory cache.

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 in terms of view and presenter/controller functionality:

  • onCreate() is a “lifecycle” method which is called by Android framework in response to framework’s internal state transitions. These transitions might or might not be related to user’s actions in the application, but the application 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 presenter/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 presenter/controller responsibilities.
  • Activity also manages the UI of the application. In the above code snippet 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.

The conclusion is that in Android, by default, Activities take on both view and presenter/controller responsibilities. If we want to implement MVC or MVP architectural patterns, it is up to us to manually enforce the separation.

Activity role:

Given that Activity, by default, are both the view and the presenter/controller, in order to implement MVC or MVP we need to decide which of these responsibilities should be extracted from it.

This question is not trivial, and there is no consensus in Android community as to which approach is better.

Many alternative implementations of MVx patterns that you might find on the internet designate Activity as view and attempt to extract the presenter/controller functionality. I don’t think that this is the optimal approach and prefer to see Activity as presenter/contoller and extract view functionality.

The justification for treating Activity as presenter/controller is given in this article: Activities in Android are not UI elements.

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

We’ve already seen that MVP and MVC 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 MVP is better for Android because it is simpler and cleaner to have independent view and model components.

If we allow the view and the model to communicate directly, we might end up in a situation when the view needs to become aware life-cycle events. Since these events are not directly related to UI management, making the view aware of them breaks the abstraction of application’s UI.

Since complete UI abstraction is very important for achieving “clean code”, I prefer MVP over MVC for Android development.

Conclusion:

In this post we reviewed MVP and MVC architectural patterns in general, and also discussed their applicability in context of Android development.

The next post (part 2) shows how to abstract UI management logic into “view” component.

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

If you liked this post, then you'll surely like my courses

Subscribe for new posts!