Android Model-View-Presenter (MVP) — Part 1

This article is a part 1 of how to implement model view presenter pattern to enhance your android code towards maintainability and test-ability.

Android Architecture and what is the problem?

If you developed before any android application you will notice that the logical code is strongly tightly coupled with the user interface elements, Android doesn’t worry too much about a separation of concerns.
It is not an easy thing to write a clean, separated layers android application, That’s OK for a small applications but when it comes to large applications that have to be tested, maintained and have a large team worked on it, we should think how to write a code in a pattern that help us to make our job done.

MVC vs. MVP for Android

Model-View-Controller (MVC):

We take a decision to write a clean, separated, testable android application. Now we have many solutions, for example the well known Model-View-Controller design pattern, it separate our application logic to 3 components:

  • Models: The central component of MVC, the model, captures the behaviour of the application in terms of its problem domain, independent of the user interface. The model directly manages the data, logic and rules of the application.
  • Views: A view can be any output representation of information, such as a chart or a diagram. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants.
  • Controller: The third part, the controller, accepts input and converts it to commands for the model or view.

Interaction between MVC Components:

In addition to dividing the application into three kinds of components, the model–view–controller design defines the interactions between them.

  • A model stores data that is retrieved according to commands from the controller and displayed in the view.
  • A view generates new output to the user based on changes in the model.
  • A controller can send commands to the model to update the model’s state (e.g. editing a document). It can also send commands to its associated view to change the view’s presentation of the model (e.g. by scrolling through a document).

Model-View-Presenter (MVP):

Model–view–presenter (MVP) is a derivation of the model–view–controller (MVC) architectural pattern, and is used mostly for building user interfaces.
In MVP the presenter assumes the functionality of the “middle-man”. In MVP, all presentation logic is pushed to the presenter.

  • The model is an interface defining the data to be displayed or otherwise acted upon in the user interface.
  • The presenter acts upon the model and the view. It retrieves data from repositories (the model), and formats it for display in the view.
  • The view is a passive interface that displays data (model) and routes user commands (events) to the presenter to act upon that data.

Difference between MVC and MVP:

In MVP:

  • View is more loosely coupled to the model. The presenter is responsible for binding the model to the view.
  • Easier to unit test because interaction with the view is through an interface
  • Usually view to presenter map one to one. Complex views may have multi presenters.

Does Android support MVC or MVP natively?

This section is part of another topic that’s speak about MVP, and i found it’s very useful to copy it here as it discussed a very important point about android design pattern — Topic: MVC and MVP architectural patterns in Android — part 1

The question is not whether the standard architecture for Android applications recommended by Google is MVC/MVP (currently, it is not), 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: 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.

MVC vs. MVP with Android Architecture

If we take a closed look on the Android’s architecture, we will found that the views (Activities, Fragments, etc.) is closely coupled without any role for controller in some cases, for example the relation between loaders and Activities or Fragments, An Activity or Fragment is responsible for calling the Loader, who should fetch data and return it to its parent. Its existence is completely tied to its parent and there is no separation between the View role (Activity/Fragment) and business logic performed by the Loader.

Also, We see that the controller can handle many views but in Android for example when we create activity, this creates an Activity class that handles it’s logic and this is closely to MVP which the relation between view and presenter is one to one.

so MVP will be the most suitable design pattern for android.

but this dose not mean that’s MVP is the suitable pattern for other needs, for example MVC is the most used design pattern for the web as it have a special way to handle web requests through controllers :

That’s enough for this part, and we will discuses in the next part how to implement Model-View-Presenter in android.

References:

Wikipedia (MVC), Wikipedia (MVP), techyourchance blog, konmik.github.io, stackoverflow